Latest web development tutorials

jQuery - AJAX load () method

jQuery load () method

jQuery load () method is a simple but powerful AJAX method.

load () method to load data from the server, and the return of data into the selected element.

grammar:

$(selector).load(URL,data,callback);

URLparameters necessary for a predetermined URL that you want to load.

Query string parameter specifies the key optionaldatasent along with the request / value pairs.

The optionalcallbackparameter is the name of the function after the load () method to complete the execution.

This is an example of the contents of the file ( "demo_test.txt") of:

<h2>jQuery AJAX 是个非常棒的功能!</h2>
<p id="p1">这是段落的一些文本。</p>

The following example will file "demo_test.txt" the content is loaded into the specified <div> element:

Examples

$ ( "# Div1") load ( "demo_test.txt").;

try it"

You can also add the jQuery selector to the URL parameter.

The following example content "demo_test.txt" file id = "p1" element, is loaded into the specified <div> element:

Examples

$ ( "# Div1") load ( "demo_test.txt # p1").;

try it"

The optional callback parameter specifies when the load () method after completion to allow callback function. The callback function can set different parameters:

  • responseTxt -contains the result of the content of the call succeeds
  • statusTXT -contains the status of the call
  • xhr -contains the XMLHttpRequest object

The following example will after the load () method to complete displaying a dialog box. If the load () method has been successful, it will show "external content loaded successfully!", And if that fails, an error message is displayed:

Examples

$("button").click(function(){
$("#div1").load("demo_test.txt",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("外部内容加载成功!");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});

try it"