The jQuery .ajax() call does it all. It has wrappers with less parameters like .get(), .post() and .load() that you can use for less verbose syntax.
You don't mention what format the data you get back is in. You need to specify in the .ajax() call. Roughly:
function addMessage(message) {
$.ajax({
url: 'add.php',
success: function() {
$("#chatmessage").text('');
},
error: function() { ... },
timeout: 3000,
data: {
message: message
}
});
}
function getMessages() {
$.ajax({
url: 'messages.php',
dataType: 'html',
timeout: 3000,
error: function() { ... },
success: function(data) {
$("#messages").html(data);
}
});
}
Note: the dataType parameter just needs to match whatever the script produces. If messages.php produces, say, an HTML list of messages then set it the dataType to "html". If that is the case, you can also simplify the code to:
function getMessages() {
$("#messages").load("message.php");
}
Note: the load() function is just a wrapper around .ajax(). Use .ajax() if you need to set things like timeouts, error handling, etc. For example:
<div id="messages"></div>
<input type="button" id="getmessages" value="Get Messages">
...
<script type="text/javascript">
$(function() {
$("#getmessages").click(function() {
$(this).attr("disabled", "true");
$.ajax({
url: 'message.php',
dataType: "html",
timeout: 5000,
error: function() {
alert("Error talking to server.");
$(this).attr("disabled", "false");
},
success: function(data) {
$("#messages").html(data);
$(this).attr("disabled", "false");
}
});
});
});
</script>
The above is a fuller example and should give you an idea of what you can use the extra parameters for. If you don't need them just use the shorthand versions.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…