ajax

0 XMLHttpRequest創(chuàng)建完對象
1 初始化完成 open
2 發(fā)送請求 send
3 正在接收數(shù)據(jù)
4 接收完成

原生js

  //創(chuàng)建XMLHttpRequest對象
  function createXHR() {
var xhr = null;
if (XMLHttpRequest) {
    xhr = new XMLHttpRequest();
}else{
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
  }

//type,url,data,async,fnSuccess,fnError

  // var data = {type:"get",url:"",data:null,async:true,success:  ,error:  };
  function ajax(data) {
//1
var xhr = createXHR();
var type,async;
type = data.type == "post" ? "post" : "get";
async = data.async?true:false;
//2
xhr.open(type,data.url,async);
//如果是post,設置請求頭
if (type == "post") {
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
//3
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            if (typeof  data.success == "function") {
                //調用回調函數(shù),傳入服務器返回的結果
                data.success(xhr.responseText);
            }
        }else{
            if(typeof data.error == "function") {
                data.error();
            }

        }
    }
}
//4
xhr.send(data.data);
  }
應用
  <script src="js/ajax.js"></script>
<script>
    window.onload = function () {
        document.getElementById("btn").onclick = function () {
            ajax({
                type:"get",
                url:"php/01-gettime.php",
                async:true,
                data:null,
                success: function (data) {
                    alert(data);
                },
                error: function () {
                    alert("錯誤");
                }
            })
        }
    }
</script>

jQuery中封裝的ajax

  jQuery的ajax請求
            $.ajax({
                url: './tologin.php',
                type: 'POST',
                dataType: 'html',
                data: {username: 'qqq',password:"123"},
                success:function(data){
                    alert(data);
                },error:function() {
                    alert(0);
                }
            })

jsonp

產生的緣由:
1,瀏覽器的同源策略
2,<script>的src不屬于同源策略
3,通過<script>的src指向的文件返回服務端數(shù)據(jù)

jQuery方法

  <script>
    $(function(){
        $.ajax({
            type:"get",
            cache:false,//不緩存
            url:"http://v.juhe.cn/weather/index?format=2&cityname=%E9%82%AF%E9%83%B8&key=e982f3629ae77eb7345b7e42f29b62ae&dtype=jsonp",
            dataType:"jsonp",
            success: function (data) {
                alert(data.reason);
            },
            error: function () {
                alert("親,錯誤");
            }
        });
    })

自己寫的小demo

  <body>
  <button id="btn">查詢正在上映的電影</button>
  <span id="msg"></span>
  <ul id="content"></ul>
  </body>
  <script>
$(function () {
    document.getElementById("btn").onclick = function () {
    var msg = document.getElementById("msg");
    msg.innerHTML = "正在拼命的加載...";
    var cb=Math.random();
    console.log(111);
    $.ajax({
            type:"get",
            // https://api.douban.com/v2/movie/in_theaters?start=0&count=10&q=undefined&callback=my_json_cb_08407925261695444
            url:"https://api.douban.com/v2/movie/in_theaters?start=0&count=10&q=undefined",
            dataType:"jsonp",
            jsonp:"callback",     //將來會替換掉地址中的  callback
            jsonpCallback:"cb",   //生成一個全局的方法  handle
            success: function (data) {
                console.log(data.subjects);
                var film=data.subjects;
                msg.innerHTML = "";
                // console.log(film[0].title);
                for(var i=0;i<film.length;i++){
                    console.log(222);
                     li=document.createElement("li");
                     li.innerHTML=film[i].title;
                     document.getElementById("content").append(li);
                }

            },
            error: function () {
                alert("error");
            }
        });

};
  });
        
            





  </script>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • AJAX 原生js操作ajax 1.創(chuàng)建XMLHttpRequest對象 var xhr = new XMLHtt...
    碧玉含香閱讀 3,274評論 0 7
  • Ajax 表單提交 在HTML中提供了表單提交的功能,我們可以通過表單把數(shù)據(jù)從前臺提交到后臺 在HTML的DOM中...
    羊烊羴閱讀 724評論 0 4
  • Ajax的基本概念及使用 同步&異步 同步:必須等待前面的任務完成,才能繼續(xù)后面的任務; 異步:不受當前主要任務的...
    magic_pill閱讀 1,976評論 0 5
  • 相信大多數(shù)前端開發(fā)者在需要與后端進行數(shù)據(jù)交互時,為了方便快捷,都會選擇JQuery中封裝的AJAX方法,但是有些時...
    TGCode閱讀 3,147評論 3 5
  • 文 / 秦未 我原來也接觸過Ajax的開發(fā),但始終沒有系統(tǒng)的學習,今天正好有時間就在慕課網學習一下,也在這里分享自...
    煮茶忘放糖閱讀 785評論 0 2