Client code (html)
Before using jQuery, we first process the html page. In this way, when we have to determine which elements to use to obtain or update the data returned by jQuery, we know how to do it. We don't need a lot of things: a peripheral div, a message paragraph, a form with a username and message text box, and a submit button. Finally, we need to add a prompt when loading information - we can easily remove it using jQuery. The following is the code:
Copy the codeThe code is as follows:
<div >
<p ><span >Loading...</span></p>
<form >
Name: <input type="text" />
Message: <input type="text" />
<input type="submit" value="ok" /><br />
</form>
</div>
Client code (jQuery)
Now, let's continue to look at the use of jQuery on the client side. First, we need to have the timestamp of the current message of life to be 0 and call the function on the server side to load the message:
timestamp = 0;
updateMsg();
We will then complete the form submitted code. jQuery allows us to add an event hook to the form's submit event, just like writing the effect of the onSubmit event directly in the html code, but there is no need to move any html code. Here is the submit event:
$("form#chatform").submit(function(){ /* Code */ });
Here we use the CSS selector syntax to refer to a form element with id 'chatform'. Once we enter the form submitted code, we can use jQuery's $.post to send a POST request. In the $.post call, we can use the id of the form element to select its value, just like we demonstrated earlier. With this, let's take a look at our ajax call:
$.post("",{ message: $("#msg").val(),
name: $("#author").val(), action: "postmsg", time: timestamp }, function(xml) {
Note that the parameter array passed here is enclosed in braces. If you have multiple parameters, you can simply split it in commas and use JSON format, as demonstrated above. You can also use jquery's ajax function to send a get request, and there will be a json-style response. You can use jQuery to convert the feedback text into a more readable form. Remember that this method only works for the get request type, but is invalid for the post we use here. Therefore, we will use the simplest XML here.
Now, let's take a look at the XML response. For code reuse, we create a function for processing xml here and call it:
addMessages(xml);
We will implement it later so that we now focus on implementing the form submission code. The code we write now is all that $.post needs, so we add braces and a prompt that returns false (return false; ). This line will invalidate the standard browser submits the form error code. The browser does not send the request to another page - because we have processed the event submission and it does not need to be processed by the browser. This is all of the code:
Copy the codeThe code is as follows:
$("form#chatform").submit(function(){
$.post("",{
message: $("#msg").val(),
name: $("#author").val(),
action: "postmsg",
time: timestamp
}, function(xml) {
addMessages(xml);
});
return false;
});
Now let's look back at the addMessages() function to process the xml response information. Use jQuery's DOM operation and traversal function to make its implementation very simple. Remember the status code I mentioned before? Now we should see how to deal with it:
if($("status",xml).text() == "2") return;
I have not mentioned the context of jQuery. The xml called here tells jQuery not to search in the html document, but to send it to us on the server side.
This line of code checks that the status code is 2, which means that a successful request has been completed but no new information is added to the form. The return keyword terminates the function call. Then we set the xml timestamp setting.
timestamp = $("time",xml).text();
Again, we get the value from the time tag of the xml.
Now, let's continue to look at jQuery's function to traverse arrays: each(); jQuery has an interesting method to traverse arrays. We use a standard selector declaration, and each() function passes a parameter-a function handles each instance of the matching element. In our example, the element is the instance of each <message> tag returned by the server. Each instance represents a message to be displayed. The parameter-the id of the instance is passed to the function. We can use jQuery's get() method to get new content-it is actually the xml of the <message> tag. The following code shows how we choose it:
$("message",xml).each(function(id) {
message = $("message",xml).get(id);
We can then use the $ function of jQuery to get the message value. Since we have all the data we need, we should add it to the message display area. This message display form has an id called 'messagewindow', so we use $("#messagewindow") to select it and use prepend() to add our data:
$("#messagewindow").prepend("<b>"+$("author",message).text()+
"</b>: "+$("text",message).text()+
"<br />");
That's all, put them together, and now our function is:
Copy the codeThe code is as follows:
function addMessages(xml) {
if($("status",xml).text() == "2") return;
timestamp = $("time",xml).text();
$("message",xml).each(function(id) {
message = $("message",xml).get(id);
$("#messagewindow").prepend("<b>"+$("author",message).text()+
"</b>: "+$("text",message).text()+
"<br />");
});
}
$.post("",{ time: timestamp }, function(xml) {
I mentioned above that we need to remove our loading message at this time, so we call the remove function on this span:
$("#loading").remove();
Then, we receive an xml response in the xml object and pass it to our addMessages function:
addMessages(xml);
Finally, we call the setTimeOut() function of javascript to execute the code intermittently. This is the complete code:
function updateMsg() {
$.post("",{ time: timestamp }, function(xml) {
$("#loading").remove();
addMessages(xml);
});
setTimeout('updateMsg()', 4000);
}
Integrate code
Now we integrate all the code together. The code can be downloaded here (this downloadable zip file). However, please see here, we added some html and css to our program:
Copy the codeThe code is as follows:
<html>
<head>
<title>Ajax with jQuery Example</title>
<script type="text/JavaScript" src=""></script>
<script type="text/JavaScript">
$(document).ready(function(){
timestamp = 0;
updateMsg();
$("form#chatform").submit(function(){
$.post("",{
message: $("#msg").val(),
name: $("#author").val(),
action: "postmsg",
time: timestamp
}, function(xml) {
$("#msg").empty();
addMessages(xml);
});
return false;
});
});
function addMessages(xml) {
if($("status",xml).text() == "2") return;
timestamp = $("time",xml).text();
$("message",xml).each(function(id) {
message = $("message",xml).get(id);
$("#messagewindow").prepend("<b>"+$("author",message).text()+
"</b>: "+$("text",message).text()+
"<br />");
});
}
function updateMsg() {
$.post("",{ time: timestamp }, function(xml) {
$("#loading").remove();
addMessages(xml);
});
setTimeout('updateMsg()', 4000);
}
</script>
<style type="text/css">
#messagewindow {
height: 250px;
border: 1px solid;
padding: 5px;
overflow: auto;
}
#wrapper {
margin: auto;
width: 438px;
}
</style>
</head>
<body>
<div >
<p ><span >Loading...</span></p>
<form >
Name: <input type="text" />
Message: <input type="text" />
<input type="submit" value="ok" /><br />
</form>
</div>
</body>
</html>
You see, using only 22 lines of javascript code, 8 lines of html and about 50 lines of php, we have implemented a complete web chat room application based on ajax. Try it and add it to your own website. Create your own ajax program, use the technology here, or you have your own good ideas. Use the code here to do telecommunications stuff. If you feel uncomfortable using xml, you can directly generate html in your application and then load it to the client. If you want, you can try the powerful xml tag attributes and jQuery's attr() function. Now you should be surprised how easy it is to implement ajax with jQuery!
[Full text ends]
Previous page123Read the full text