jQuery開發之Ajax,jqueryajax

來源:互聯網
上載者:User

jQuery開發之Ajax,jqueryajax

1,load()方法
(1)load()方法是jQuery中最常用和最簡單的Ajax方法,能載入遠程HTML代碼,並插入代碼中。它的結構為:

load(url [,data] [,callback])

load()方法解釋如下表所示

範例程式碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=GB18030"><title>jQuery test </title><script type ="text/javascript" src ="jquery.js" ></script><link href="styles.css" rel="stylesheet" type="text/css" /><script type ="text/javascript">$(document).ready(function(){    $("#send").click(function(){        $("#resText").load("test.html");    });});</script></head><body><div class ="comment"><h6>張三:</h6><p class ="para">沙發</p></div><div class ="comment"><h6>李四:</h6><p class ="para">板凳</p></div><div class ="comment"><h6>王五:</h6><p class ="para">地板</p></div><input type ="button" id ="send" value ="Ajax擷取" /><div class ="comment">已有評論:</div><div id = "resText"></div></body></html>

運行效果:
沒有單擊按鈕的時候

單擊按鈕後

(2) 篩選載入的html文檔
核心代碼如下:

$("resText").load("test.html .para")

運行效果如下:

(3)傳遞方式
load()方法的傳遞方式根據data來自動指定,如果沒有參數傳遞,則採用 GET方式傳遞,反之,則採用POST方式。範例程式碼如下:

無參數傳遞是get方法$("resText").load("test.php",function(){})$("resText").load("test.php",{name:"rain",age:"22"},function(){})

(4) 回調參數
對於必須在載入完成後再能進行的操作,load()方法提供了回呼函數(callback),該函數有三個參數分別代表請求返回的內容,請求狀態和XMLHttpRequest對象,jQuery代碼如下:

$("resText").load("test.php",function(responseText,textStatus,XMLHttpRequest){//responseText    返回的內容//textStatus    請求狀態  success, error, notmodified,timeout//XMLHttpRequest對象})

2,$.get()方法和$.post()方法
$.get()方法使用GET方法進行非同步請求。
它的結構為:

$.get(url [,data] [,callback] [,type])

參數解釋如下:

$.post() 方法範例程式碼如下:

3,$.getScript()方法 和$.getJson()方法
(1), 有時候,在頁面初次載入時取得所需的全部javaScript()檔案是完全沒有必要的。雖然可以在需要哪個 JavaScript的時候,動態建立<script> 標籤,jQuery代碼如下:

$(document.createElement("script")).attr("src","test.js").appendTo("head");

或者

$("<script type ='text/javaScript' src ='test.js'/>").appendTo("head");

用$.getScript() 更加的簡單

$.getScript("test.js")

(2) $.getJson()方法
jQuery範例程式碼如下:

(4) $.ajax()方法

$.ajax() 方法是jQuery中Ajax的最底層實現。結構為:

$.ajax(options)

參數說明如下:


範例程式碼如下:

$(function(){$("send").click(function(){$.ajax({type:"GET",url:"test.js",dataType:"script"});});})

jQuery中Ajax全域事件還有其他幾種,如下:

注意:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.