我正在尝试使用ajax从我的php函数中获取数据数组但是遇到困难。这是我的php函数:
function dallas_db_facebook_make_post () {
global $wpdb;
$query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$fbposttext = $result['text'];
$fbposttime = $result['time'];
$array = array('post' => $fbposttext, 'posttime' => $fbposttime);
echo json_encode($array);
}
}
这是我的jQuery函数:
function send_fb_post() {
jQuery.ajax({
type: "POST",
url: my_ajax.ajaxurl,
dataType: 'json',
data: {
'action': 'dallas_db_facebook_make_post'
},
beforeSend: function() {
},
success: function(data){
var jq_json_obj = jQuery.parseJSON(data);
console.log(jq_json_obj);
},
error: function(){
},
});
};
答案 0 :(得分:0)
一些修正,你需要在for循环完成时输出总数组。以下功能将起作用我认为
function dallas_db_facebook_make_post () {
global $wpdb;
$query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$fbposttext = $result['text'];
$fbposttime = $result['time'];
$array[] = array('post' => $fbposttext, 'posttime' => $fbposttime);
}
echo json_encode($array);
}
答案 1 :(得分:0)
function dallas_db_facebook_make_post () {
global $wpdb;
$query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$fbposttext = $result['text'];
$fbposttime = $result['time'];
$array[] = array('post' => $fbposttext, 'posttime' => $fbposttime);
}
echo json_encode($array);
}
Ajax电话:
$.ajax({
type: "POST",
url: "your url",
dataType: "json",
data: {action: 'dallas_db_facebook_make_post'},
success: function(response) {
console.log(response);
}
});
并检查您在控制台中看到的内容。如果您使用chrome作为浏览器,请右键单击并单击inspect元素。你看到了控制台。
我认为你可以获得如下元素:response [index] [' post'];