JQuery Ajax Example Study Notes

Source: Internet
Author: User

JQuery Ajax is a very good plug-in that simplifies the original ecological js ajax. With jquery ajax, it is as simple as eating, below I have sorted out some examples of jquery ajax applications to learn from and hope the article will be helpful to you.

Using jQuery makes Ajax easier. JQuery provides some functions to make simple work easier and complex work no longer complicated.

The most common use of Ajax is to load an HTML code to a certain area of the page. To do this, simply select the required elements and use the load () function. The following is an example of updating statistics:

The Code is as follows: Copy code

('{Stats'{.load('stats.html ');

Generally, we only need to pass some parameters to a page on the server. As you expected, using jQuery is very simple. You can use $. post () or $. get (), which is determined by the required method. If necessary, you can also pass an optional data object and callback function. Listing 4 shows a simple example of sending data and using callback.

Listing 4. Use Ajax to send data to the page

The Code is as follows: Copy code

$. Post ('Save. cgi ',{

Text: 'My string ',

Number: 23

}, Function (){

Alert ('your data has been saved .');

});

If you really need to write some complex Ajax scripts, you need to use the $. ajax () function. You can specify xml, script, html, or json. jQuery automatically prepares suitable results for the callback function, so that you can use the results immediately. You can also specify beforeSend, error, success, or complete callback functions to provide users with more feedback on the Ajax experience. In addition, some other parameters are available. You can use them to set the Ajax request timeout, or set the "last modification" status on the page. Listing 5 shows an example of retrieving an XML document using some of the parameters I mentioned.

Listing 5. $. ajax () makes Ajax complex and simple

The Code is as follows: Copy code

$. Ajax ({

Url: 'document. xml ',

Type: 'get ',

DataType: 'xml ',

Timeout: 1000,

Error: function (){

Alert ('error loading XML document ');

},

Success: function (xml ){

// Do something with xml

}

});

After the success callback function returns an XML document, you can use jQuery to retrieve this XML document in the same way as retrieving HTML documents. This makes it quite easy to process XML documents and integrates content and data into your Web site. Listing 6 shows an extension of the success function, which adds a list item to the Web page for each element in XML.
Listing 6. Using jQuery to process XML documents

The Code is as follows: Copy code

Success: function (xml ){

$ (Xml). find ('item'). each (function (){

Var item_text = $ (this). text ();

$ ('

 
')

. Html (item_text)

. AppendTo ('ol ');

});

}

View A jQuery Ajax instance demonstration

The Code is as follows: Copy code

<Html>
<Head>
<Title> jQuery Ajax instance demonstration </title>
</Head>
<Script language = "javascript" src = "../lib/jquery. js"> </script>
<Script language = "javascript">

$ (Document). ready (function ()
{
$ ('# Send_ajax'). click (function (){
Var params = $ ('input'). serialize (); // serialized form value
$. Ajax ({
Url: 'ajax _ json. php', // background Handler
Type: 'post', // data transmission method
DataType: 'json', // accept the data format
Data: params, // data to be transmitted
Success: update_page // return function (function name here)
});
});

// $. Post () method:
$ ('# Test_post'). click (function (){
$. Post (
'Ajax _ json. php ',
{
Username: $ ('# input1'). val (),
Age: $ ('# input2'). val (),
Sex: $ ('# input3'). val (),
Job: $ ('# input4'). val ()
},
Function (data) // return function
{
Var myjson = '';
Eval ('myjson = '+ data + ';');
Certificate ('{result'}.html ("name:" + myjson. username + "<br/> job:" + myjson ['job']);
}
);
});

// $. Get () method:
$ ('# Test_get'). click (function ()
{
$. Get (
'Ajax _ json. php ',
{
Username: $ ("# input1"). val (),
Age: $ ("# input2"). val (),
Sex: $ ("# input3"). val (),
Job: $ ("# input4"). val ()
},
Function (data) // return function
{
Var myjson = '';
Eval ("myjson =" + data + ";");
$ ("# Result" cmd.html (myjson. job );
}
);
});
});

Function update_page (json) // return the function entity. The parameter is XMLhttpRequest. responseText.
{
Var str = "name:" + json. username + "<br/> ";
Str + = "age:" + json. age + "<br/> ";
Str + = "Gender:" + json. sex + "<br/> ";
Str + = "job:" + json. job + "<br/> ";
Str + = "append test:" + json. append;
$ ("# Result" example .html (str );
}
</Script>
<Body>

<Div id = "result" style = "background: orange; border: 1px solid red; width: 300px; height: 200px;"> </div>
<Form id = "formtest" action = "" method = "post">
<P> <span> input name: </span> <input type = "text" name = "username" id = "input1"/> </p>
<P> <span> input age: </span> <input type = "text" name = "age" id = "input2"/> </p>
<P> <span> input Gender: </span> <input type = "text" name = "sex" id = "input3"/> </p>
<P> <span> input job: </span> <input type = "text" name = "job" id = "input4"/> </p>
</Form>
<Button id = "send_ajax"> submit </button>
<Button id = "test_post"> POST submission </button>
<Button id = "test_get"> GET submit </button>

</Body>
</Html>


PHP file ajax_json.php:

The Code is as follows: Copy code

<? Php
// $ Arr = $ _ POST; // if you send data in the $. get () mode, change it to $ _ GET. Or simply: $ _ REQUEST
$ Arr =$ _ REQUEST;
$ Arr ['append'] = 'test string ';
// Print_r ($ arr );
$ Myjson = my_json_encode ($ arr );
Echo $ myjson;

Function my_json_encode ($ phparr)
{
If (function_exists ("json_encode "))
{
Return json_encode ($ phparr );
}
Else
{
Require_once 'json/json. class. php ';
$ Json = new Services_JSON;
Return $ json-> encode ($ phparr );
}
}
?>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.