ajax

2023-05-25

常见的HTTP状态码
状态码:
200 请求成功.一般用于GET和POST方法 OK
301 资源移动.所请求资源移动到新的URL,浏览器自动跳转到新的URL Moved Permanently
304 未修改.所请求资源未修改读取缓存数据 Not Modified
400 请求语法错误,服务器无法理解 Bad Request
404 未找到资源,可以设置个性"404页面" Not Found
500 服务器内部错误 internal Server Error

编写ajax
1.创建Ajax对象
2.连接服务器
3.发送请求
4.接受返回

1.创建Ajax对象
IE6:ActiveXObject("Microsoft.XMLHTTP");//IE6已死,可以不考虑了
XMLHttpRequest();
例:var request = new XMLHttpRequest();
2.连接服务器
open(method,url,async);
open(发送请求方法"GET/POST" ,(请求地址"文件名") ,是否异步传输)
例: request.open("GET","get.json",true);
3.发送请求
send(string)
在使用GET方式请求时无需填写参数
在使用POST方式时参数代表着向服务器发送的数据

//完整的GET请求
var oAjax = new XMLHttpRequest();//创建Ajax对象
oAjax.open("GET","create.php",true);//连接服务器
oAjax.send();//发送请求

//完整的POST发送请求
var oAjax = new XMLHttpRequest();//创建
oAjax.open("POST","create.php",true);//"POST"
oAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");//设置HTTP头信息.必须在open与send之间,否则出现异常.
oAjax.send("name=陈二狗&sex=男");//发送给服务器的内容

4.接收返回-请求状态监控
XMLHttpRequset取得响应:
responseText 获得字符串形式的响应数据
responseXML 获得XML形式的响应数据
status和statusText 以数字和文本方式返回HTTP状态码
getAllResponseHeader() 获取所有的响应报头
getResponseheader() 查询响应中的某个字段的值

onreadystatechange事件
通过监听onreadystatechange事件,来判断请求的状态.
readyState属性:响应返回所处状态

状态码 状态 所处位置
0 (未初始化) 即httpRequest对象已创建,但是open()方法还没调用
1 (载入) 即请求已经open()过了,但是send()方法还没调用
2 (载入完成) 即send()过了,但是data数据还没返回
3 (解析) 动态交互,即data数据已经接收到了,但是responseText内容会获取
4 (完成) 响应内容解析完成,可以在客户端调用了

例子:

<script type="text/javascript">
ajax({
url: "data.php", //请求地址
type: "POST", //请求方式
data: { name: "super", age: 20 }, //请求参数
dataType: "json",
success: function (response, xml) {
console.log(response)
// 此处放成功后执行的代码
},
fail: function (status) {
// 此处放失败后执行的代码
}
});

function ajax(options) {
options = options || {};
options.type = (options.type || "GET").toUpperCase();
options.dataType = options.dataType || "json";
var params = formatParams(options.data);

//创建 - 非IE6 - 第一步
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
} else { //IE6及其以下版本浏览器
var xhr = new 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.fail && options.fail(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);
//console.log(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("&");
}
</script>

ajax的相关教程结束。

《ajax.doc》

下载本文的Word格式文档,以方便收藏与打印。