首页 > 语言 > JavaScript > 正文

浅谈jQuery异步对象(XMLHttpRequest)

2024-05-06 14:50:09
字体:
来源:转载
供稿:网友

我们先来看看异步对象五部曲

这是post请求的、

代码如下:
 //1.00创建异步对象
            var xhr = new XMLHttpRequest();
            //2.0
            xhr.open("post", url,params, true);
            //3.0将参数使用Formdata属性传递
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            //4.0设置回调函数
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    alert(xhr.responseText);
                }
            }
            //5.0传递参数
            xhr.send(params);

结合get请求做一个异步对象的封装

get 请求中的

  xhr.setRequestHeader("If-Modified-Since", "0"); 是为了清除缓存

而post请求的

代码如下:
 xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

是为了传输方式
在<from method='post' type="">
<from>中的type可以得到三种方式,其中包括application/x-www-form-urlencoded
 
代码如下:
var ajaxHelp = {
    CreatXHR: function () {
        //创建异步对象
        var xhr = new XMLHttpRequest();
        return xhr;
    },
    //ajax的get请求
    AjaxGet: function (url, callBack) {
        this.AJaxCommon("get", url, null, callBack);
    },
    //ajax的post请求
    AjaxPost: function (url, params, callBack) {
        this.AJaxCommon("post", url, params, callBack);
    },
    AJaxCommon: function (method, url, params, callBack) {
        //1.0
        var xhr = this.CreatXHR();
        //2.0

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选