我使用jQuery Ajax form post将消息写入db表,如下所示:
functions.php
add_action(\'wp_ajax_send_projectmessage\', \'send_projectmessage\');
function send_projectmessage() {
global $wpdb;
$wpdb->insert( //insert stuff to db table));
wp_send_json_success();
}
JS:
$(\'#form-pm\').on(\'submit\',function(e) {
var mydata = {
\'action\': \'send_projectmessage\',
\'projectid\': projectid,
\'message\': message
};
var ajaxRequest =
$.ajax({
url: admin_ajax.ajax_url,
type: \'post\',
data: mydata
});
ajaxRequest.done(function(data) { console.log(data); });
ajaxRequest.fail(function(jqXHR) { alert(jqXHR); });
e.preventDefault();
});
一切正常,数据被插入到我的数据库表中。
现在,这是我显示消息的方式:
<div id="messages">
<?php
$messages = load_projectmessages($projectid);
foreach ($messages as $message) {
//make a <table><tr><td> with $message->themessage
}
?>
</div>
<form id="form-pm>
<!-- input fields and submit here -->
</form>
load_projectmessages
在同一个
functions.php:
function load_projectmessages($projectid) {
global $wpdb;
$sql_displaymessages = $wpdb->prepare("sql stuff", $projectid );
$projectmessages = $wpdb->get_results($sql_displaymessages);
return $projectmessages;
wp_die();
}
我的问题是,
where/when 我要打电话吗
load_projectmessages
? 我是否应该修改整个JS ajax代码来同时显示新数据?
最合适的回答,由SO网友:Qaisar Feroz 整理而成
按如下方式修改代码:
add_action(\'wp_ajax_send_projectmessage\', \'send_projectmessage\');
function send_projectmessage() {
global $wpdb;
$wpdb->insert( //insert stuff to db table));
// Call your function to retrieve your data and send it to browser
$messages = load_projectmessages($projectid);
wp_send_json_success($messages);
}
通过修改此项通过JS显示数据
ajaxRequest.done(function(data) { console.log(data); });
到这个
ajaxRequest.done(function(data) {
// Put markup for retrieved data here
// for example
var o = "<table><tr><td>Project ID</td><td>Message</td></tr>";
for (i=0; i<=data.length; i++){
o .= "<tr><td>"+data.projectid+"</td><td>"+data.message"+</td></tr>";
}
o .= "</table>";
$(#messages).html(o);
});
另外,请确保函数返回的是数组而不是对象,因此请按如下方式修改它:
function load_projectmessages($projectid) {
global $wpdb;
$sql_displaymessages = $wpdb->prepare("sql stuff", $projectid );
// Add ARRAY_A to get result in an associative array
$projectmessages = $wpdb->get_results($sql_displaymessages, ARRAY_A);
return $projectmessages;
// Not needed
// wp_die();
}
我希望这会有所帮助。