ajax小结

2017-07-23  本文已影响0人  qhaobaba

在平时的开发项目中,难免接触前端的知识,需要写接口,有时候用到js中的ajax跨越请求,总结了ajax的写法。

开始之前,需要准备两个文件,ajax.php ;ajax.html

1.ajax的基本步骤(ajax.php)

//1.创建对象
    var ajax = new XMLHttpRequest();
    // alert(typeof ajax);

//2.建立连接
ajax.open('get', 'ajax.php?id=5', true);

//3.发送请求
ajax.send();

//4.准备事件处理结果
ajax.onreadystatechange = function()
{
    if (ajax.readyState == 4 && ajax.status == 200) {
        //请求: request
        //响应: response
        var res = ajax.responseText;

        // alert(res);
        document.write(res);
    }
}

ajax,有同步异步的区别?异步:把小弟派出去了,什么时候回来,什么时候处理它,主程序继续执行,不会等待。同步:(比较少用)会在send这一步等待,主程序不会继续执行。method:请求的类型;GET 或 POST 。

2.ajax封装为函数(ajax.php)

<script>
 function get(url, func)
 {
     var ajax = new XMLHttpRequest();
     ajax.open('get', url, true);
     ajax.send();
     ajax.onreadystatechange = function()
     {
         if (ajax.readyState == 4 && ajax.status == 200) {
             var res = ajax.responseText;

             func(res);
         }
     }
 }

 //回调 + 匿名
 get('1.php', function(res){
     alert(res);
 })

 get('ajax.php', function(res){
     console.log(res);
 })

/*
 get('1.php', chuli);
 function chuli(res)
 {
     alert(res);
 }

 get('ajax.php', chuli2);
 function chuli2(res)
 {
     console.log(res);
 }
 */
</script>

这样封装好,就方便我们使用了,tp框架,ecshop,ecstore,都有自己的封装的ajax。

3.jq中的ajax请求(ajax.php)

$.ajax({
     url: 'ajax.php?id=5',
     dataType: 'json',    //指定返回数据的类型:xml, html, script, json, text, _default (不要骗他)
     type: 'get',    //设置请求的类型:get(默认) post
     // data: 'name=123&age=18',    //传输的数据(有两种格式)
     data: {age:8},    //传输的数据
     async: true,    //同步异步:true 默认异步     false 同步 
     success: function(res) {
         // alert(typeof res);
         // alert(res.id);
         alert(123);
     },
     error: function(a){
         alert('出错鸟~~~');
     }
 });

4.ajax跨域问题(ajax.php)

协议、域名、端口这三个有任何一个不同,就跨域了。ajax本身是不可以跨域的,通过产生一个script标签来实现跨域。因为script标签的src属性是没有跨域的限制的。其实设置了dataType: 'jsonp'后,$.ajax方法就和ajax XmlHttpRequest没什么关系了,取而代之的则是JSONP协议。JSONP是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问。

实现ajax的跨域请求,有几种方法,这儿写一种通过‘jsonp’,实现跨域的方法

<script type="text/javascript">     
   var url = 'http://localhost/other.php?act=get_article';
$.ajax({
    type : "get",
    url :url, 
    jsonp: "callbackparam",
    jsonpCallback:"jsonpCallback1",
    success : function(data){
        var obj = eval(data);
        //处理接收到的数据
    },
    //end
    error:function(e){
        alert("error");
    }
});                
</script>
上一篇 下一篇

猜你喜欢

热点阅读