ajax总结

ajax总结

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

  开始以前,须要准备两个文件,ajax.php ;ajax.htmlphp

 

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

复制代码
//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)java

复制代码
<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。ajax

 

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

复制代码
$.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>
复制代码

  知识更新很快,学习很重要。当回过头,感受这些很简单的时候,说明本身在进步,在成长...

相关文章
相关标签/搜索