JSON
JavaScript 转 JSON: JSON.stringify(ele, 数组或函数, 缩进)
一个参数:
var book = {
title:"you",
authors:"me",
year:2011,
edition:3
};
var jsonText = JSON.stringify(book);
// jsonText:{"title":"you","authors":"me","year":2011,"edition":3}
两个参数:
var book = {
title:"you",
authors:"me",
year:2011,
edition:3
};
如果是数组:
var jsonText = JSON.stringify(book, ["title", "authors"]);
// jsonText:{"title":"you","authors":"me"} (筛选出title和authors的键值对)
如果是函数:
function rep(key, value) {
switch(key) {
case "title" :
return "miss you";
case "authors" :
return "mm.me";
case "year" :
return 2008;
default :
return value;
}
}
var jsonText = JSON.stringify(book, rep);
// jsonText:{"title":"miss you","authors":"mm.me","year":2008,"edition":3}
注意:如果将defalut换成 case "edition" ,得到的是undefined
三个参数:var jsonText = JSON.stringify(book, null, 4);
// 得到jsonText:
{
"title": "you",
"authors": "me",
"year": 2011,
"edition": 3
}
每个键值对前都有4个空格,还可以写成"--"之类的字符串
JavaScript对象中的值如果是函数或者undefined会忽略这对键值对
JSON 转 JavaScript :JSON.parse(JSON对象,函数)
同上面只有一个参数的例子得到的JSON格式 // jsonText:{"title":"you","authors":"me","year":2011,"edition":3}
var parse = JSON.parse(jsonText, function(key, value) {
//每个对象的成员都执行这里的代码
if(key == "title") {
return new People(); // 改变了title里的值,变成了一个People的实例
}else {
return value;
}
}
// parse:{title: People, authors: "me", year: 2011, edition: 3}
所以就能调用People的方法sayHi(),parse.title.sayHi()
AJAX
①创建对象
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft XMLHTTP");
}
②设置请求方式和地址
xhr.open("POST", "xxx.php", true);
xhr.open("GET", "xxx.php"+str, true); // str是user:"haha"&pwd:"123" 这个格式的数据
第一个参数:发送方式,一般同这两种"GET","POST"
"GET":有长度限制,会将数据放在URL中,会保留在历史记录中
"POST":没有长度限制,会将数据放到请求头中
第二个参数:请求地址
第三个参数:boolean值,true为异步(不填默认就是true),false为同步 (一般都用true)
③发送请求
xhr.send();
注意:如果是POST请求,要在open和send之间插入
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(str);
④监听状态onreaderstatechange(放在open之前,确保跨浏览器兼容)
xhr.onreaderstatechange = function(e) {
// 获取状态信息:xhr.readystate,有五中状态,分别是0~5
// 0:未初始化(open之前)
// 1:服务器连接已建成(open)
// 2:请求已接收(拿到响应头)
// 3:请求处理中(正在下载响应头)
// 4:请求已完成,且响应已就绪
if(xhr.readyState == 4) {
if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){ // 判断状态码,是否在这些范围内,表示成功
xhr.responseText // 获取服务器返回的信息(XML用xhr.responseXML)
} else { // 不成功 };
}
注意:如果是通过GET请求,URL:"xxx.php"+str,那么IE会认为这个URL只有一种结果(我修改数据,返回来的数据不会有任何变化)
解决:在后面添加随机数即可"xxx.php"+str+Math.random()
模拟jQuery中的AJAX实现代码在前面的兼容代码那
xhr.aborb():中断请求
encodeURLComponent(str):转换成URL编码
getResponseHeader("serve"):获取单个响应头信息
getAllResponseHeaders():获取所有响应头信息
同源策略:协议相同(http https) 域名相同(www) 端口号相同(80)
AJAX不能直接 不同源之间相互访问
JSONP
但是script标签可以发送不同源地址请求,JSONP就是利用这一特性
jQuery里的JSONP:$.ajax({ ... , dataType: "jsonp",...})