drcigvoy48900 2014-05-14 20:12
浏览 58
已采纳

如何使用jquery在ajax响应中发送一堆json对象

I'm playing with jQuery's $.ajax and I'm not sure how I should be doing the following:

Here's my javascript (right now its just embedded in the html page)

$.ajax({
    type: 'GET',
    url: 'DBConnect.php',
    data: '',
    dataType: 'json', 
    success: function(data) {

        console.dir(data);
    },
    error:function (xhr, ajaxOptions, thrownError) {
        dir(thrownError);
        dir(xhr);
        dir(ajaxOptions);
    }
});

Here is what DBConnect.php looks like:

$username = "root";
$pass = "pass";
$host = "127.0.0.1";
$dbname = "test";

//queries
$table = "events";
$fetchAll = "SELECT * FROM $table";

try {
    $DB = new PDO("mysql:host=$host;dbname=$dbname", $username, $pass);
    //_WARNING uncommented when debugging
    $DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
    //$DB->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $query = $DB->query($fetchAll);
    $query->setFetchMode(PDO::FETCH_OBJ);

    while($row = $query->fetch()) {
        echo json_encode($row);
    }

} catch(PDOException $e) {
    echo $e->getMessage();
}

$DB = null;

Doing this I get a syntax error. I thought I could get away with returning every row as a json object, but clearly that doesn't work. I could just add all the row objects to one array and convert that to json, but I wanted to know if there was a better\more efficient way to do this.

  • 写回答

1条回答 默认 最新

  • douzong6649 2014-05-14 20:15
    关注

    Change the while loop:

    $temp = array();
    while($row = $query->fetch()) {
        $temp[] = $row;
    }
    echo json_encode($temp);
    

    Try this, and let me know if that helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料