2016-07-10 69 views
0

我想从我的php函数使用ajax获取数据的数组,但有一个困难的时候。这里是我的PHP函数:如何使用jQuery ajax获取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

您是否正在向PHP函数发送数据,期望数组返回数组的形式,还是要将数组发送到PHP端? – da1lbi3

+0

我想从我的jQuery函数中使用的数组形式的PHP函数中获取数据。 – user715564

回答

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); 

} 
+0

谢谢,但没有奏效。 – user715564

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作为浏览器,请右键单击并单击检查元素。你有看到控制台。

我想你可以得到这样的元素:response [index] ['post'];

+0

控制台中没有返回任何内容。如果我做了'error:function(error){console.log(error)}'之类的东西,那么它看起来就像在控制台中显示的那样。 – user715564

+0

好的,请求在网络标签下的chrome中说什么?你可以发布截图吗? – da1lbi3

+0

我可以截图,但它只是说表单数据操作:dallas_db_facebook_make_post – user715564

相关问题