1.创建XMLHttpRequest对象
- function createXMLHTTPRequest() {
-
-
-
- var xmlHttpRequest;
- if (window.XMLHttpRequest) {
-
- xmlHttpRequest = new XMLHttpRequest();
-
- if (xmlHttpRequest.overrideMimeType) {
- xmlHttpRequest.overrideMimeType("text/xml");
- }
- } else if (window.ActiveXObject) {
-
-
-
- var activexName = [ "MSXML2.XMLHTTP", "Microsoft.XMLHTTP" ];
- for ( var i = 0; i < activexName.length; i++) {
- try {
-
-
- xmlHttpRequest = new ActiveXObject(activexName[i]);
- if(xmlHttpRequest){
- break;
- }
- } catch (e) {
- }
- }
- }
- return xmlHttpRequest;
- }
2.get请求
- function get(){
- var req = createXMLHTTPRequest();
- if(req){
- req.open("GET", "http://test.com/?keywords=手机", true);
- req.onreadystatechange = function(){
- if(req.readyState == 4){
- if(req.status == 200){
- alert("success");
- }else{
- alert("error");
- }
- }
- }
- req.send(null);
- }
- }
3.post请求
- function post(){
- var req = createXMLHTTPRequest();
- if(req){
- req.open("POST", "http://test.com/", true);
- req.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=gbk;");
- req.send("keywords=手机");
- req.onreadystatechange = function(){
- if(req.readyState == 4){
- if(req.status == 200){
- alert("success");
- }else{
- alert("error");
- }
- }
- }
- }
- }
post请求需要设置请求头
4. readyState与status:
readyState有五种状态:
0 (未初始化): (XMLHttpRequest)对象已经创建,但还没有调用open()方法;
1 (载入):已经调用open() 方法,但尚未发送请求;
2 (载入完成): 请求已经发送完成;
3 (交互):可以接收到部分响应数据;
4 (完成):已经接收到了全部数据,并且连接已经关闭。
如此一来,你应该就能明白readyState的功能,而status实际是一种辅状态判断,只是status更多是服务器方的状态判断。关于status,由于它的状态有几十种,我只列出平时常用的几种:
100——客户必须继续发出请求
101——客户要求服务器根据请求转换HTTP协议版本
200——成功
201——提示知道新文件的URL
300——请求的资源可在多处得到
301——删除请求数据
404——没有发现文件、查询或URl
500——服务器产生内部错误
原生Ajax书写
原文:http://www.cnblogs.com/xuan52rock/p/4578601.html