dongwuzun4630 2016-07-10 22:20
浏览 95

如何使用jQuery ajax获取php数组数据

I am trying to get an array of data from my php function using ajax but having a difficult time. Here is my php function:

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

    }   

}

Here is my jQuery function:

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(){
        },
    });
};
  • 写回答

2条回答 默认 最新

  • duanleixun2439 2016-07-10 22:24
    关注

    Some correction, you need to output the total array when for loop completes. below function will work i think

    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);   
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记