Using JQuery will make Ajax as simple as it gets. JQuery provides a number of functions that make simple work easier, and complex work becomes less complex.
The most common use of Ajax is to load a piece of HTML code into an area of the page. To do this, simply select the element you want, and then use the load () function. The following is an example for updating statistics:
| The code is as follows |
Copy Code |
|
$ (' #stats '). Load (' stats.html '); |
Typically, we simply pass some parameters to a page in the server. As you would expect, using JQuery to do this is a very simple operation. You can use $.post () or $.get (), which is determined by the method you want. You can also pass an optional data object and callback function, if needed. Listing 4 shows a simple example of sending data and using callbacks.
Listing 4. Using Ajax to send data to a 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 do need to write some complex Ajax scripts, you need to use the $.ajax () function. You can specify that XML, script, HTML, or json,jquery will automatically prepare the appropriate results for the callback function so that you can use the result immediately. You can also specify Beforesend, error, success, or complete callback functions to provide users with more feedback about the Ajax experience. In addition, there are other parameters available that you can use to set the timeout for the Ajax request, or to set the status of the page "last modified." Listing 5 shows an example of retrieving an XML document using some of the parameters I mentioned.
Listing 5. $.ajax () makes Ajax simpler by complexity
| 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
}
}); |
When the success callback function returns an XML document, you can use JQuery to retrieve the XML document in the same way that it retrieves an HTML document. This makes processing XML documents quite easy, and integrates content and data into your Web site. Listing 6 shows an extension of the success function, which adds a list item to a WEB page for each element in the 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 ');
});
} |
See a jquery Ajax instance demo
| The code is as follows |
Copy Code |
|
<title>jquery Ajax Example Demo </title>
<script language= "javascript" src= ". /lib/jquery.js "></script>
<script language= "JavaScript" >
$ (document). Ready (function ()
{
$ (' #send_ajax '). Click (function () {
var params=$ (' input '). Serialize (); Serializing the value of a form
$.ajax ({
URL: ' ajax_json.php ',//Background handler
Type: ' Post ',//Data send mode
DataType: ' json ',//Accept data format
Data:params,//data to be passed
Success:update_page//Return functions (here is the name of the function)
});
});
//$.post () mode:
$ (' #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 + '; ');
$ (' #result '). HTML ("Name:" + myjson.username + "<br/> work:" + myjson[ ' Job ']);
}
);
});
//$.get () mode:
$ (' #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"). HTML (myjson.job);
}
);
});
});
Function Update_page (JSON)//Return function entity with parameter Xmlhttprequest.responsetext
{
var str= name: ' +json.username+ ' <br /> ";
str+= "Age:" +json.age+ "<br/>";
str+= "Sex:" +json.sex+ "<br/>";
str+= "work:" +json.job+ "<br/>";
str+= "Append test:" +json.append;
$ ("#result"). 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> Enter Name: </span><input type= "text" name= "username" id= "input1"/></p>
<p><span> input Age: </span><input type= "text" Name= "ages" id= "Input2"/></p>
<p><span> Enter Gender: </span><input type= "text" name= "Sex" id= "INPUT3"/></p>
<p><span> input work: </span><input type= "text" name= "job" id= "Input4"/></p>
</form>
<button id= "Send_ajax" > Submit </button>
<button id= "Test_post" >post submit </button>
<button id= "Test_get" >get submit </button>
</body>
|
PHP file ajax_json.php:
| code is as follows |
copy code |
|
<?php
//$arr = $_post//If you send the data in $.get (), change 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);
}
}
|