您的位置:首页 > 理论基础 > 计算机网络

ajax基础(1)

2015-11-19 22:45 507 查看
ajax 4步曲

//1、打开浏览器
var xhr = null;
if (window.XMLHttpRequest) {  //兼容处理
xhr = new XMLHttpRequest()
}else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//2、输入地址
xhr.open('GET' , '1.txt' ,true);

//3、提交
xhr.send();

//4、返回结果
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {  //xhr.status 服务器的状态
alert(xhr.responseText)
}else {
alert('啊噢,出错了:  '+ xhr.status)
}

};
}


get与post存在的一些问题

1、get方式的缓存问题 :
在url?后面连接一个随机数,时间戳
xhr.open('get','shoname.php?username=BOB&age=100&'+new Date().getTime(),true)

2、get方式乱码,编码encodeURI
xhr.open('get',"shoname.php?username='+encodeURI('老王')+'&age=100&"+new Date().getTime(),true)

3、post方式:数据放在send()方法里作为参数传递
(1)请求头:指定发送的文档类型(编码)
xhr.setRequestHeader('content-type','application/x-www-form-urlencode');
(2)传参,如果传递username=老王,不需要编码encodeURI了,因为请求头已经声明了
xhr.send('username=BOB&age=100')

4、post没有缓存问题。

5、stringify : 把一个对象转成对应的字符串
6、parse : 把字符串转成对应的对象,字符串格式的json的key值,必须用双引号引起来。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ajax xmlhttprequest