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 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题