[英]converting from prototype to jquery
我正在嘗試從一個從mysql數據庫獲取數據的php文件中對div進行簡單的ajax更新。 一個函數填充div,另一個函數將消息添加到數據庫,並在單擊提交按鈕時調用。 我想知道是否有人可以在jquery中給我他們的等價物。 以下是原型版本。
<script>
function getMessages(){
new Ajax.Updater('chat','messages.php', {
onSuccess:function(){
window.setTimeout( getMessages, 3000 );
}
});
}
getMessages();
</script>
<script>
function addmessage(){
new Ajax.Updater('chat','add.php',{
method:'post',
parameters: $('chatmessage').serialize(),
onSuccess: function() {
$('messagetext').value = '';
}
});
}
</script>
jQuery .ajax()調用可以完成所有操作。 它有包含較少參數的包裝器,如.get(),. postt()和.load(),您可以使用它們來減少冗長的語法。
您沒有提到您獲取的數據的格式。您需要在.ajax()調用中指定。 大致:
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);
}
});
}
注意: dataType參數只需匹配腳本生成的任何內容。 如果messages.php產生一個HTML消息列表,那么將dataType設置為“html”。 如果是這種情況,您還可以將代碼簡化為:
function getMessages() {
$("#messages").load("message.php");
}
注意: load()函數只是.ajax()的包裝器。 如果需要設置超時,錯誤處理等內容,請使用.ajax()。例如:
<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>
以上是一個更全面的示例,應該讓您了解可以使用額外參數的內容。 如果您不需要它們,只需使用速記版本。
$.ajax({
type: "GET",
url: "messages.php",
data: "name=John&location=Boston",
success: function(){
window.setTimeout(getMessages,3000);
}
});
第二次添加消息
$.ajax({
type: "POST",
url: "add.php",
data: $('#chatmessage').param(),
success: function() {
$('messagetext').value = '';
}
});
有關詳細信息,請查看http://docs.jquery.com/Ajax
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.