整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

JavaScript封装 ajax GET和POST

JavaScript封装 ajax GET和POST请求


装文件public.js完整代码:

(function(){
        //用于得到一个dom元素
        var $=function(id){
        				return document.getElementById(id);
        };
        //用于得到一个ajax对象
        $.init=function(){
                try{return new XMLHttpRequest()}catch(e){}
                try{return new ActiveXObject('Microsoft.XMLHTTP')}catch(e){}
                alert('error');
        };
        //用于发送ajax的get请求
        $.get=function(url,data,callback,type){
                var xhr=$.init();
                if(data!=null){
                url=url+'?'+data;
        }
        xhr.onreadystatechange=function(){
                if(xhr.readyState==4 && xhr.status==200){
                        if(type==null){
                        type='text';
                        }
                        if(type=='text'){
                        callback(xhr.responseText);
                        }
                        if(type=='xml'){
                        callback(xhr.responseXML);
                        }
                        if(type=='json'){
                        callback(eval('('+xhr.responseText+')'));
                        }
                }
        };
        xhr.open('get',url);
        xhr.setRequestHeader("If-Modified-Since","0");
        xhr.send(null);
        };
        //用于发送ajax的post请求
        $.post=function(url,data,callback,type){
                var xhr=$.init();
                xhr.onreadystatechange=function(){
                        if(xhr.readyState==4 && xhr.status==200){
                                //如果没有传递type参数,让type的值为text
                                if(type==null){
                                type='text';
                                }
                                if(type=='text'){
                                callback(xhr.responseText);
                                }
                                if(type=='xml'){
                                callback(xhr.responseXML);
                                }
                                if(type=='json'){
                                callback(eval('('+xhr.responseText+')'));
                                }
                        }
                };
                xhr.open('post',url);
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send(data);
}
window.$=$;
})();


语言类似于jQuery

理解:

1、添写一个自调用匿名函数

(function (){
})();

在一个项目中,可能会引用多个js框架,如果函数名相同,会有命名冲突,定义匿名函数没有名称,就不会冲突,

但匿名函数不能执行,所以需要使用以上格式让其自动执行一次。

2、封装一个函数,用于dom元素的获取

var $=function(id){
return document.getElementById(id);
};

但$是局部变量,外面不能直接使用,所以:

window.$=$;

表示为全局对象window添加一个"$"的属性,这个属性的值是当前局部变量$的值。

所以在外部,如果想获取某个dom元素,可以直接:

$('content');

3、封装一个函数,用于创建ajax对象

因为之前,我们将一个函数赋值给了$,函数也是对象,所以$也就是一个对象

$.init=function(){
        try{return new XMLHttpRequest()}catch(e){}
        try{return new ActiveXObject('Microsoft.XMLHTTP')}catch(e){}
        alert('error');
};

表示为对象$添加一个新的方法:init

当然, 也可以添加其它方法

4、封装ajax的get请求

为对象 $添加一个get方法,参数有三个

url:表示ajax请求的页面地址

data:表示get请求时所需要传递的参数

callback:当ajax得到正确数据后,所执行的回调函数,也就是参数callback接收的参数应该是一个函数。

$.get=function(url,data,callback,type){
        var xhr=$.init();
        if(data!=null){
        				url=url+'?'+data;
        }
        xhr.open('get',url);
        xhr.setRequestHeader("If-Modified-Since","0");
        xhr.onreadystatechange=function(){
                if(xhr.readyState==4 && xhr.status==200){
                      if(type==null){
                              type='text';
                      }
                      if(type=='text'){
                              callback(xhr.responseText);
                      }
                      if(type=='xml'){
                              callback(xhr.responseXML);
                      }
                      if(type=='json'){
                              callback(eval('('+xhr.responseText+')'));
                      }
        		}
        };
        xhr.send(null);
};


5、封装post请求

为对象 $添加一个post方法,参数有三个

url:表示ajax请求的页面地址

data:表示post请求时所需要传递的参数

callback:当ajax得到正确数据后,所执行的回调函数,也就是参数callback接收的参数应该是一个函数。

$.post=function(url,data,callback,type){
var xhr=$.init();
xhr.open('post',url);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onreadystatechange=function(){
        if(xhr.readyState==4 && xhr.status==200){
                //如果没有传递type参数,让type的值为text
                if(type==null){
                        type='text';
                }
                if(type=='text'){
                        callback(xhr.responseText);
                }
                if(type=='xml'){
                        callback(xhr.responseXML);
                }
                if(type=='json'){
                        callback(eval('('+xhr.responseText+')'));
                }
        }
    };
    xhr.send(data);
}

当调用ajax请求时,可以使用这种形式:

$.method(页面地址,传递参数,处理函数);

那么对应的方法中callback参数就指向了这个处理函数,所以

callback(xhr.responseText);

相当于

处理函数(xhr.responseText);

6、添加返回值类型

现在,我们在ajax程序中,可以使用三种数据形式:

1)字符串

2)xml

3)json

我们需要完善这个框架,可以返回不同类型的数据,再进行不同的处理。

首先,为get和post方法添加第四个参数:type,表示期望得到的返回值类型

$.post=function(url,data,callback,type){}

再根据type值的不同,返回对应的数据

if(type==null){
      type='text';
}
if(type=='text'){
        callback(xhr.responseText);
}
if(type=='xml'){
        callback(xhr.responseXML);
}
if(type=='json'){
        callback(eval('('+xhr.responseText+')'));
}

调用形式

$.method(请求地址,参数,处理函数,数据类型);

TML:完成页面的内容展示

CSS:完成页面样式的控制,美化页面,完成页面的布局。

表单:用于采集用户输入的数据。用于和服务器进行交互。

form:用于定义表单的。可以定义一个范围(代表用户采集数据的范围)

属性:action:指定提交数据的url(指的就是把数据提交到哪里)

method:指定提交方式

分类:一共有7种,2种比较常用。

get:1.请求参数会在地址栏显示

2.请求参数的长度是有限制的。

3.请求不安全

post:1.请求参数不会在地址栏显示,会封装在请求体中。

2.请求参数的长度没有限制

3.较为安全

表单里面的数据要想被提交,必须指定它的name属性


Query get() 和 post() 方法用于通过 HTTP GET 或 POST 请求从服务器请求数据。


HTTP 请求:GET vs. POST

两种在客户端和服务器端进行请求-响应的常用方法是:GET 和 POST。

  • GET - 从指定的资源请求数据

  • POST - 向指定的资源提交要处理的数据

GET 基本上用于从服务器获得(取回)数据。注释:GET 方法可能返回缓存数据。

POST 也可用于从服务器获取数据。不过,POST 方法不会缓存数据,并且常用于连同请求一起发送数据。


jQuery $.get() 方法

$.get() 方法通过 HTTP GET 请求从服务器上请求数据。

语法:

$.get(URL,callback);

必需的 URL 参数规定您希望请求的 URL。

可选的 callback 参数是请求成功后所执行的函数名。

下面的例子使用 $.get() 方法从服务器上的一个文件中取回数据:

实例

$("button").click(function(){ $.get("demo_test.php",function(data,status){alert("数据: " + data + "\n状态: " + status); });});

$.get() 的第一个参数是我们希望请求的 URL("demo_test.php")。

第二个参数是回调函数。第一个回调参数存有被请求页面的内容,第二个回调参数存有请求的状态。

提示: 这个 PHP 文件 ("demo_test.php") 类似这样:

demo_test.php 文件代码:

<?phpecho'这是个从PHP文件中读取的数据。';?>


jQuery $.post() 方法

$.post() 方法通过 HTTP POST 请求从服务器上请求数据。

语法:

$.post(URL,data,callback);

必需的 URL 参数规定您希望请求的 URL。

可选的 data 参数规定连同请求发送的数据。

可选的 callback 参数是请求成功后所执行的函数名。

下面的例子使用 $.post() 连同请求一起发送数据:

实例

$("button").click(function(){ $.post("/try/ajax/demo_test_post.php", {name:"菜鸟教程", url:"http://www.runoob.com"}, function(data,status){alert("数据: \n" + data + "\n状态: " + status); });});

$.post() 的第一个参数是我们希望请求的 URL ("demo_test_post.php")。

然后我们连同请求(name 和 url)一起发送数据。

"demo_test_post.php" 中的 PHP 脚本读取这些参数,对它们进行处理,然后返回结果。

第三个参数是回调函数。第一个回调参数存有被请求页面的内容,而第二个参数存有请求的状态。

提示: 这个 PHP 文件 ("demo_test_post.php") 类似这样:

demo_test_post.php 文件代码:

<?php$name=isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '';$url=isset($_POST['url']) ? htmlspecialchars($_POST['url']) : '';echo'网站名: ' . $name;echo"\n";echo'URL 地址: ' .$url;?>

如您还有不明白的可以在下面与我留言或是与我探讨QQ群308855039,我们一起飞!