ajax使用及代码表示

最近学习了ajax,记录一下学习写过的代码和一些问题

一、原生ajax

var xhr = null;
if(window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("get",url,true);
xhr.send(null);
xhr.onreadystatechange = function() {
if(xhr.readyState ==4 && xhr.status == 200) {
var responseText = JSON.parse(xhr.responseText);
if(responseText.status == 0) {

}
}

说明:

1.responseXML是一个对象,可以调用对象的api解析,而responseText是字符串要用var data= JSON.parse(str)将字符串转化为json对象

2.JSON.stringify(data);将json对象转化为字符串

3.如果提交方式改为post,需要使用xhr来模仿表单提交,具体方法为:设置xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

4.解决缓存问题:在url后面传参时传入当前的毫秒数     (new Date()).getTime()

如:http://cdn.weather.hao.360.cn/sed_api_area_query.php?grade=town&_jsonp=loadTown&code=0101&_=1477837767684&_="+(new Date()).getTime();

二、通过xhr实现ajax通信的一个限制来源于跨域安全策略,解决方案:jsonp

function handleResponse(response){

console.log(response.ip+response.name);

}

var script = document.createElement("script");

script.src="http://freegeoip.net/json?callback=handleResponse"

document.head.appendChild(script);

 

 

ajax在jquery中的用法

&.ajax({
type:"post",
url:"./jsonp.php?username=username",
dataType:"html",
data:{username:"qqq",password:"123"}.两种方式都可以这样传
success: function(json){//success就是回调函数,解析数据就是这
console.log(json);
},
error:function(){
console.log("fail");
}
})

说明:

data选项既可以包含一个查询字符串,比如 key1=value1&key2=value2 ,也可以是一个映射,比如 {key1: 'value1', key2: 'value2'} 。如果使用了后者的形式,则数据再发送器会被转换成查询字符串。

 

jsonp在jquery里的用法:

&.ajax({
type:"get",
async:true,//异步标志位
url:url,
dataType:"jsonp",
data:{username:"qqq",password:"123"},
jsonp:"cb",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(默认为:callback)
jsonpCallback:"callback",//自定义的jsonp回调函数名,默认为jQuery自动生成的随机函数名(类似:jQuery110201451414_4323443(["zhangsan","lise"]))
success: function(json){//success就是回调函数,解析数据就在这
//console.log(json);
}
error:function(){
console.log("fail");
}
})

 

posted on 2016-11-03 21:45  分享是一种快乐  阅读(2431)  评论(0编辑  收藏  举报