关于Ajax的写法

关于Ajax的写法

Ajax 即“Asynchronous Javascript And XML " (异步JavaScript 和 XML ),能够在无需重新加载整个网页的情况下,更新部分网页(异步更新)。

  • jq请求Ajax
类型内容类别解释
url地址相对地址/绝对地址例子: url: ‘http://jingdong.index.json’、url: ‘/request/ajaxtest’、url: ‘request/ajaxtest’
dataType数据类型json一般都是json数据类型
type请求类型GET/POSTGET请求在地址栏中有显示你的请求信息;POST请求不会,所以POST请求安全性比较高,当你要发送账号和密码时,最好使用POST请求;
timeout超时number当发送请求超过number秒后,还没接受到信息就报错error

注:请求回来的数据是json格式的,需要将数据转成js对象格式才能被浏览器所识别,所以要调用JSON.parse(data)函数

$.ajax({
				url:'3.query.php',//地址
				dataType:'json',//数据类型
				type:'GET',//类型
				timeout:2000,//超时

				//请求成功
				success:function(data,status){
				var res = data;
					//alert(data);
					 res = JSON.parse(res);	//解析数据
					//alert(status);
				},
				//失败/超时
				error:function(XMLHttpRequest,textStatus,errorThrown){
					if(textStatus==='timeout'){
						alert('請求超時');
						setTimeout(function(){
							alert('重新请求');
						},2000);
					}
					//alert(errorThrown);
				}
			})
  • 原生js封装Ajax

    onreadystatachange:存储函数,每当readyStata属性改变时,就会调用该函数。
    readyStata:有XMLHttpRequest的状态(0到4)
    0:请求未初始化
    1:服务器连接已建立
    2:请求已接收
    3:请求处理中
    4:请求已完成,响应已就绪

    status:200表示"ok",404表示”未找到页面"
    status==404,表示找不到网页(no find)

    使用post提交时,要设置表单提交时的内容类型
    xhr.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”)

    POST提交的数据有一定的格式,所以需要格式话数据后才能提交
//调用Ajax函数
ajax({
	url: '',
	type: 'GET/POST',
	dataType: 'json',
	data: {name: "hello",age: "12"},
	success:function(response,xml){
		//请求成功后执行的代码
	},
	error: function(status){
		//请求失败后执行的代码
	}
	
});


//封装ajax
function ajax(options){
	options = options||{}
	options.type = (options.type||'GET').toUpperCase()
	options.dataType = options.dataType || 'json'
	params = formatParams(options.data)
	
	var xhr
	//非ie6
	if(window.XMLHttpRequest){
		xhr = new XMLHttpRequest()
	}else{
		//ie6及以下版本浏览器
		xhr = ActiveXObject('Microsoft.XMLHTTP')
	}
	
	xhr.onreadystatechange = function(){
		if(xhr.readyState==4){
			var status = xhr.status
			if(status>=200 && status<=300)
			{
				options.success && options.success(xhr.responseText,xhr.responseXML)
			}else{
				options.error&&options.error(status)
			}
		}
	}
	
	if(options.type == 'GET'){
		xhr.open('GET',options.url+'?'+params,true)
		xhr.send(null)
	}else if(options.type == 'POST'){
		xhr.open('POST',options.url,true)
		//设置表单提交时的内容类型
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
		xhr.send(params)
	}
}

//格式化数据
function formatParams(data){
	var arr = [];
	for(var name in data){
		arr.push(encodeURIComponent(name)+'='+encodeURIComponent(data[name]))
	}
	arr.push(('v='Math.random()).replace('.',''))
	return arr.join('&')
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值