使用AJAX动态更新数据库中的文本
我一直在努力学习AJAX,因此我可以简单地用数据库中的新文本动态更新我的网页,因为看起来所有的ajax教程都是更复杂的例子,涉及将数据写入数据库
我正在处理的页面只是一个PHP脚本,需要将注册和ID号发布到它,然后它会从数据库中显示消息(经常更新)。 我目前在页面顶部有一个“更新消息”按钮,它发送命令以更新消息,但它需要页面刷新才能工作。
我只想使用ajax动态刷新消息。 以下是我到目前为止所写的内容,基于我在使用Jquery Ajax从Mysql中检索数据时所发现的内容,但它不起作用,因为我不知道如何将注册和id号作为参数传递给php脚本使用ajax并显示响应。
请注意, sendPushNotification
函数不相关且工作正常(用于发送命令以更新消息)。
readmessages.php
Inbox $(document).ready(function(){ }); function sendPushNotification(id){ var data = $('form#'+id).serialize(); $('form#'+id).unbind('submit'); $.ajax({ url: "send_message.php", type: 'GET', data: data, beforeSend: function() { }, success: function(data, textStatus, xhr) { $('.txt_message').val(""); }, error: function(xhr, textStatus, errorThrown) { } }); return false; } function updateText(registration, rowid) { $.ajax({ //create an ajax request to readmessages.php type: "GET", url: "readmessages.php", dataType: "html", //expect html to be returned success: function(response){ $("#responsecontainer").html(response); } }); } <form id="" name="" method="post" onsubmit="return sendPushNotification('')"> <input type="hidden" name="regId" value=""/> <input type="submit" class="send_btn" value="Update Messages" onclick="return updateText(, );"/> //Attempts to call function to update text once button is pressed (not functioning) getInbox($rName); //calls the database to retrieve messages echo nl2br($messagelist); //Displays message list that I want to update include './logout.php'; ?>
任何帮助将不胜感激!
编辑:更新的行包含适当的引号:
<input type="submit" class="send_btn" value="Update Messages" onclick="return updateText('', '')"/>
您需要包含数据以及ajax请求,
data: {registration: registration, rowid: rowid},
并且还将类型设置为POST,因为在php端您正在检索POST变量。
就这样……
function updateText(registration, rowid) { $.ajax({ //create an ajax request to readmessages.php type: "POST", url: "readmessages.php", dataType: "html", //expect html to be returned data: {registration: registration, rowid: rowid}, success: function(response){ $("#responsecontainer").html(response); }
要在AJAX
和PHP
之间进行通信,您必须了解两件事:
1)如果您使用PHP's
$_POST
,您的AJAX
必须表示数据的发布 ,并且,
2)如果您使用PHP's
$_GET
,您的AJAX
必须表示获取数据。
所以,你做不到:
$.ajax({ //create an ajax request to readmessages.php type: "GET",//NOTICE THIS GET thingi... url: "readmessages.php", dataType: "html", //expect html to be returned success: function(response){ $("#responsecontainer").html(response); }
并做:
你宁愿在两边使用'POST'
或'GET'
所以,如果你想简单地POST
,你的AJAX可能看起来像:
$.post('url_goes_here.php',{myDataXXX:comes_here},function(response_here){ console.log(response_here); })
和你的PHP
如果你想简单地GET
,你的AJAX可能看起来像:
$.get('url_goes_here.php',{myDataXXX:comes_here},function(response_here){ console.log(response_here); })
和你的PHP
希望有帮助......