ajax學習筆記,ajax完全學習手冊

來源:互聯網
上載者:User

ajax學習筆記,ajax完全學習手冊

有點亂,可以戳原文:http://www.ido321.com/1512.html

一、js原生髮送Ajax請求

關於Ajax的簡單介紹,可以戳此:DOM筆記(五):JavaScript的常見事件和Ajax小結

<html>    <head>        <meta http-equiv="content-type" content="text/html;charset=utf-8">        <title>demo</title>    </head>    <body>        <button id="btn">ajax載入</button>        <div id="div1">            <p>下面是ajax載入的內容</p>            <p id="ajaxcontent"></p>        </div>    </body>    <script type="text/javascript">        //返回xhr執行個體        function createXHR()        {            if(window.XMLHttpRequest)            {                // code for IE7+, Firefox, Chrome, Opera, Safari                    return new XMLHttpRequest();            }            else            {                // code for IE6, IE5                return  new ActiveXObject("Microsoft.XMLHTTP");            }        }        //xhr事件處理        function xhrHandle()        {            var xhr = createXHR();            var res;            xhr.onreadystatechange=function()            {                if(this.readyState === 4)                {                    if(this.status >= 200  && this.status < 300)                    {                        document.getElementById('ajaxcontent').innerHTML = this.responseText;                    }                    else                    {                        document.getElementById('ajaxcontent').innerHTML ='Error';                    }                }            }            xhr.open('GET','./ajaxdemo.php?a=12&b=34');            xhr.send(null);        }        document.getElementById('btn').addEventListener('click',xhrHandle,false);    </script></html>

 

對於get請求,send()不帶參數,或者設定null。若send()要帶參數,則必須為post請求,還需要佈建要求頭

xhr.open('POST','./ajaxdemo.php');xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");    xhr.send('a=56&b=78');

 

ajaxdemo.php:

<?php          $fir = $_POST['a'];          $sec = $_POST['b'];          echo "a=",$fir,'<br/>','b=',$sec;?>

 

載入前

載入後

 

二、JQuery的Ajax請求方式

1、load(url.param,callback):向url發送一個帶選擇性參數param的Ajax請求,可指定一個回呼函數。

url 必選,Ajax請求地址(字串)
param 可選,指定請求所帶的參數(字串|對象|數組);若指定為對象或者數組(鍵值對方式),則發起POST請求,若為字串,則發起GET請求。
callback(response,status,xhr) 可選,請求完成時調用的函數。
額外的參數可選

  • response – 包含來自請求的結果資料
  • status – 包含請求的狀態(”success”, “notmodified”, “error”, “timeout” 或 “parsererror”)
  • xhr – 包含 XMLHttpRequest 對象

 

<html>    <head>        <meta http-equiv="content-type" content="text/html;charset=utf-8">        <title>demo</title>        <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>    </head>    <body>        <div id="div1">            <p>下面是ajax載入的內容</p>            <p id="ajaxcontent"></p>        </div>    </body>    <script type="text/javascript">        $('#ajaxcontent').load('./ajaxdemo.php',{a:342,b:'test'});    </script></html>

 

效果同上類似。load()也可以直接載入xml、html或者html的某個片段內容。

<html>    <head>        <meta http-equiv="content-type" content="text/html;charset=utf-8">        <title>demo</title>        <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>    </head>    <body>        <div id="div1">            <p>下面是ajax載入的內容</p>            <p id="ajaxcontent"></p>        </div>    </body>    <script type="text/javascript">        $('#ajaxcontent').load('./ajaxhtml.html #ajaxhtml');    </script></html>

 

載入ajaxhtml.html中 id是ajaxhtml的片段。ajaxhtml.html如下

<html>    <head>        <meta http-equiv="content-type" content="text/html;charset=utf-8">        <title>ajax</title>    </head>    <body>        <div id="div1">            <p>下面是ajax要載入的內容</p>            <p id="ajaxhtml">demo.html檔案中請求了這裡的資料</p>        </div>    </body></html>

 

結果:    2、$.get/post(url,param,callback,type):向url發送帶參數的get請求,返回xhr執行個體
url 必選,Ajax請求地址(字串)
param 可選,指定請求所帶的參數(字串|對象|數組)
callback(response,status,xhr) 可選,請求完成時調用的函數。
額外的參數可選

  • response – 包含來自請求的結果資料
  • status – 包含請求的狀態(”success”, “notmodified”, “error”, “timeout” 或 “parsererror”)
  • xhr – 包含 XMLHttpRequest 對象
type 可選。規定預計的伺服器響應的資料類型。預設地,jQuery 將智能判斷。

可能的類型:

  • “xml”
  • “html”
  • “text”
  • “script”
  • “json”
  • “jsonp”

 

介面採用上面的,修改js

$('#btn').on('click',function(){            $.get('./demo.txt',function(res)            {                $('#ajaxcontent').text(res)            });        });

 

從demo.txt中載入一段文本,儲存為utf-8編碼,不然中文會亂碼

$.post()形式和$.get()基本一樣,不再贅述。

 

3、$.getJSON(url,param,callback):向url發起GET請求,把響應結果轉為JSON字串,傳遞給callback。返回xhr執行個體。相當於在$.get()中,type指定為json.

$('#btn').on('click',function(){            $.getJSON('./ajaxdemo.php',function(res)            {                $.each(res,function(index,item)                {                    $("#ajaxcontent").append(                        '<p>'+index+'-->'+item                        );                });            });        });

 

json資料

<?php       $jsondata =' {"name":"dwqs","blog":"http://www.ido321.com","age":21}';       echo $jsondata;?>

 

結果

$.each()用於遍曆json對象,方法接受兩個參數,第一個是需要遍曆的對象集合(JSON對象集合),第二個是用來遍曆的方法,這個方法又接受兩個參數,第一個是遍曆的index,第二個是當前遍曆的值。

$.ajax(options)或者$.ajax(url[,options]):返回一個xhr執行個體。options是一個對象,用於定義ajax請求參數。完整的參數列表:https://api.jquery.com/jQuery.Ajax/

$.get()、$.post()和$.getJSON()都是簡寫的$.ajax(),其等價於

$.ajax({url:url,data:data,success:callback,dataType:dataType});

 

改寫上面的demo

$('#btn').on('click',function(){            $.ajax({                url:'./ajaxdemo.php',                dataType:'json',                success:function(res){                    $.each(res,function(index,item)                    {                        $("#ajaxcontent").append(                            '<p>'+index+'-->'+item                        );                    });                }            });        });

 

對於沒有指定的ajax參數,則使用預設值。如果發起很多相似的ajax請求,則可用$.ajaxSetup(options)設定預設值,options同$.ajax()中的options

 

三、Ajax事件

1、事件類型

事件名稱 類型 說明
ajaxStart 全域 當Ajax請求開始時觸發
beforeSend 局部 發起請求前觸發,可在發送請求之前修改xhr執行個體或者return false 取消請求
ajaxSend 全域 發起請求前觸發,可在發送請求之前修改xhr執行個體
success 局部 請求返回一個成功響應時調用
ajaxSuccess 全域 請求返回一個成功響應時調用
error 局部 請求返回一個錯誤響應時調用
ajaxError 全域 請求返回一個錯誤響應時調用
complete 局部 請求結束時調用
ajaxComplete 全域 請求結束時調用
ajaxStop 全域 請求結束並且沒有其它並發的請求處於啟用狀態時調用

 

$('body').on('ajaxStart ajaxStop ajaxSend ajaxSuccess ajaxError ajaxComplete',function(e){    console.log(e.type);});

 

2、ajax事件建立器

Ajax提供了6個事件建立器:ajaxComplete(callback)、ajaxSuccess((callback)、ajaxError(callback)、ajaxStart(callback)、ajaxSend(callback)和ajaxStop(callback),callback是回調的事件處理函數,函數上下文是在其上建立的dom元素

$("#txt").ajaxStart(function(){  $("#wait").css("display","block");});$("#txt").ajaxComplete(function(){  $("#wait").css("display","none");});

 

 

四、Ajax參數解析

1、JQuery.param(object,traditional):建立數組或對象的序列化表示,object是要進行序列化的數組或對象,traditional規定是否使用傳統的方式淺層進行序列化(參數序列化)

var params = { width:1900, height:1200 };var str = jQuery.param(params);$("#results").text(str);

 

結果

width=1680&height=1050

 

var myObject = {     a: {         one: 1,          two: 2,          three: 3     },      b: [1,2,3] }; var str = jQuery.param(myObject); var ttt=decodeURIComponent(str); $("#ajaxcontent").html(str+"<br/>"+ttt);
結果
a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3

 

2、.serialize():建立以標準 URL 編碼錶示的文本字串。它的操作對象是代表表單元素集合的 jQuery 對象。返回格式化的查詢字串

3、.serializeArray() :方法通過序列化表單值來建立對象數組(名稱和值),此方法返回的是 JSON 對象而非 JSON 字串。

假設存在一個表單

<form>     <select name="single">          <option>Single</option>          <option>Single2</option>     </select>     <select name="multiple" multiple="multiple">          <option selected="selected">Multiple</option>          <option>Multiple2</option>          <option selected="selected">Multiple3</option>     </select><br/>     <input type="checkbox" name="check" value="check1"/> check1     <input type="checkbox" name="check" value="check2" checked="checked"/> check2     <input type="radio" name="radio" value="radio1" checked="checked"/> radio1     <input type="radio" name="radio" value="radio2"/> radio2</form>

 

console.dir($('form').serializeArray()); jQuery.each( $('form').serializeArray(), function(i, field){      $("#ajaxcontent").append(field.value + " ");});

 

輸出:

Single Multiple Multiple3 check2 radio1

 


原文:http://www.ido321.com/1512.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.