您的位置:首页 > 其它

AJAX 总结

2016-01-07 10:47 155 查看
<pre style="font-family: Consolas; font-size: 12pt;"><pre name="code" class="javascript" style="background-color: rgb(255, 255, 255);">    /*创建ajax核心对象*/
/*get方法*/
var xhr = getXhr();
xhr.open("GET","php?key=value&key=value...");    //与服务器简历链接,使用get方式向服务器发送请求
xhr.send(null);                                  //发送请求
xhr.onreadystatechange = function(){             //触发事件
if(xhr.readyState==4&&xhr.status==200){      //服务器响应完成  并且   本次请求成功
var data = xhr.responseText;             //用data 存储  从服务器端发送回来的json格式的*字符串*数据
var obj = JSON.parse(data);              //用JSON.parse()来解析   比较安全不用eval('('+data+')')
}else{
console.log("发生错误"+xhr.status);
}
};

/*post方法*/
var xhr = getXhr();
xhr.open("POST","php");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("key=value&key=value...");
xhr.onreadystatechange = function(){
if(xhr.readyState==4&&xhr.status==200){
var data = xhr.responseText;
var obj = JSON.parse(data);
}else{
console.log("发生错误"+xhr.status);
}
}
/*构造XMLHttpRequest函数*/
function getXhr(){
if(window.XMLHttpRequest){
//Mozilla浏览器
xhr = new XMLHttpRequest();
}else{
//IE浏览器
if(window.ActiveXObject){
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
}
return xhr;
}

JSON.parse()与eval()的区别:

eval() 这种解析方法,不会在意json数据的合法性,如果里面有js代码,会直接执行。如果存在window.location等链接	   累的恶意代码,这样是很危险的。(string,number,boolean)

JSON.parse()  则不会,如果存在不合法的类型,会直接报错。


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: