AJAX 原生学习笔记

AJAX 是 Asynchronous JavaScript and XML 的缩写,直译就是异步的js和XML。

含义:
不重新加载整个页面的情况下,与服务器交换数据并更新部分网页。

知识点:
XMLHttpRequest对象是 AJAX 基础。
现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)。

原生使用流程:
1.创建XHR对象

var xhr = new XMLHttpResquet();

2.XHR向服务器发请求

xhr.open("get",url,async);
xhr.send(string);

eg:

    xhr.open("POST",'http://localhost:8080/getName',true);
    xhr.send();

a.设置发送头

setRequestHeader(header,value)

eg:

// 设置POST请求的请求头  
xmlrequest.setRequestHeader("Content-Type"  
        , "application/x-www-form-urlencoded"); 

b.加参数
GET:

    xhr.open("GET",'http://localhost:8080/getName?id=001&area=0536',true);
    xhr.send();

POST:

    xhr.open("POST",'http://localhost:8080/getName,true);
    xhr.send("id=001&area=0536");

3.服务器响应

获取数据:
通过XMLHttpRequest 对象的 responseText 或 responseXML 属性。

事件:
当 readyState 改变时,就会触发 onreadystatechange 事件。

readyState:
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪

status:
200: “OK”
404: 未找到页面
更多状态码:https://baike.baidu.com/item/HTTP%E7%8A%B6%E6%80%81%E7%A0%81/5053660?fr=aladdin

*当 readyState 等于 4 且状态为 200 时,表示响应已就绪:
eg:

xhr.onreadystatechange=function()
{
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        console.log('result:'+xmlhttp.responseText);
    }
}

附:
jQuery的方式:

    type : "POST",
    url : REQUEST_BASE_PATH + "/LoginController/login",
    data : {
        "name":'ch'
        "pwd":'123'
    },
    dataType : "json",
    success : function(data) {
        console.log('data:回调成功数据');
    },
    error : function(data) {}
});

EXT的方式:

Ext.Ajax.request({
     url: 'ajax_demo/sample.json',

     success: function(response, opts) {
         var obj = Ext.decode(response.responseText);
         console.dir(obj);
     },

     failure: function(response, opts) {
         console.log("server-side failure with status code" + response.status);
     }
 });

猜你喜欢

转载自blog.csdn.net/Dorothy1224/article/details/80050207