簡短地說,在不重載整個網頁的情況下,AJAX 通過后臺加載數據,并在網頁上進行顯示,也就是異步加載。
load() 方法從服務器加載數據,并把返回的數據放入被選元素中。 語法:
$(selector).load(URL,data,callback);url:必需參數,請求的urldata:可選參數,發送至服務器的 key/value 數據。callback:可選參數,請求完成時(不需要是success的)的回調函數。例如: 可以將h3中的內容換成test文件中的內容
$("h3").load("../../doc/test");也可以將test文件中的p元素加載到h3中
$("h3").load("../../doc/test p");回調函數可以設置不同的參數:
responseTxt - 包含調用成功時的結果內容statusTXT - 包含調用的狀態通過遠程 HTTP GET 請求載入信息。
語法:
$(selector).get(url,data,success(response,status,xhr),dataType)success:可選。規定當請求成功時運行的函數。 額外的參數:
response - 包含來自請求的結果數據status - 包含請求的狀態xhr - 包含 xmlHttPRequest 對象dataType:可選,規定預計的服務器響應的數據類型。 默認地,jQuery 將智能判斷。 可能的類型:”xml”,”html”,”text”,”script”,”json”,”jsonp”
通過 HTTP POST 請求從服務器載入數據 語法:
jQuery.post(url,data,success(data, textStatus, jqXHR),dataType)通過 HTTP GET 請求載入并執行 javaScript 文件。
語法:
jQuery.getScript(url,success(response,status))通過 HTTP 請求加載遠程數據。 語法:
jQuery.ajax([settings])settings:可選。用于配置 Ajax 請求的鍵值對集合??梢酝ㄟ^ $.ajaxSetup() 設置任何選項的默認值。
常見的請求參數:
url:請求的url。data:發送到服務器的數據。type:請求方式。dataType:預期服務器返回的數據類型。success:請求成功后的回調函數。error:請求失敗時調用此函數。complete:請求完成后回調函數 (請求成功或失敗之后均調用)。beforeSend:發送請求前可修改 xmlhttpRequest 對象的函數,如添加自定義 HTTP 頭。cache:類型為Boolean,默認為true,dataType為 script 和 jsonp 時默認為false,設置為false將不緩存此頁面。實例:
$.ajax({ // the URL for the request url: "post.php", // the data to send (will be converted to a query string) data: { id: 123 }, // whether this is a POST or GET request type: "GET", // the type of data we expect back dataType : "json", // code to run if the request succeeds; // the response is passed to the function success: function( json ) { $( "<h1/>" ).text( json.title ).appendTo( "body" ); $( "<div class=/"content/"/>").html( json.html ).appendTo( "body" ); }, // code to run if the request fails; the raw request and // status codes are passed to the function error: function( xhr, status, errorThrown ) { alert( "Sorry, there was a problem!" ); console.log( "Error: " + errorThrown ); console.log( "Status: " + status ); console.dir( xhr ); }, // code to run regardless of success or failure complete: function( xhr, status ) { alert( "The request is complete!" ); }, beforeSend: function() { }, cache: true //false});新聞熱點
疑難解答