dongseshu0698 2014-01-31 15:53
浏览 55
已采纳

jquery ajax使用php json编码获取数据库结果

I have this php code that is call using jQuery ajax that queries a database and gets results and then json encode the results

//$rows is another query
foreach($rows as $row) {

    $sql = 'SELECT field1, field2 FROM table WHERE field1= :field';

    $stmt = $db->prepare($sql);
    $stmt->bindValue(':field', trim($row['field_1']));
    $stmt->execute();

    $array = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($array);
}

The outputting json looks like this

[{"field1":"J1","field2":"0088","field3":"2928868"}][{"field1":"J2","field2":"0171","field3":"2928868"}][{"field1":"J2","field2":"0249","field3":"2928868"}]

The problem I'm getting is processing it in the Ajax response. What I would like to do i s loop through each of the array/rows and display the data but the responseText shows an error.

I thought it should look this but i don't know for definite.

[{"field1":"J1","field2":"0088","field3":"2928868"},{"field1":"J2","field2":"0171","field3":"2928868"},{"field1":"J2","field2":"0249","field3":"2928868"}]

My question is, am i doing the json_encode correctly and how do i output each of the rows?

$.ajax({
    type: "POST",
    url: "check.php",
    data: { order: order },
    dataType: "json",
    cache: false,
    success: function(response) {

        if(response.length != 0) {

            //output results here
        }
        else {
            $('#foo').text('Order number not found!!');
        }

        // set the focus to the order input
        $('#order').focus().val('');
    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
        console.log('An Ajax error was thrown.');
        console.log(XMLHttpRequest);
        console.log(textStatus);
        console.log(errorThrown);
    }
});
  • 写回答

1条回答 默认 最新

  • douque9815 2014-01-31 15:55
    关注

    You should JSON encode the entire output, instead of outputting the json encoded version of each row:

    $output = array();
    
    //$rows is another query
    foreach($rows as $row) {
    
        $sql = 'SELECT field1, field2 FROM table WHERE field1= :field';
    
        $stmt = $db->prepare($sql);
        $stmt->bindValue(':field', trim($row['field_1']));
        $stmt->execute();
    
        $array = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
        $output[] = $array;
    }
    
    echo json_encode($output);
    

    Answering your question, to work with your JSON in JavaScript, you treat it as if it were an array of objects. You can even use jQuery to help loop through the results for you with $.each:

        if(response.length != 0) {
    
              $.each(response, function(index, row) {
    
                  console.log(row);
                  // Access your row variables like so:
                  // row.field1, row.field2, row.field3, etc.
              }
    
        }
    

    If you prefer natively looping through, you can do the following:

        // Let i start at zero. If the response array length is less than i, execute the block, then increment i by 1.
        for(var i = 0; response.length < i; i += 1) {
    
        }
    

    Related Question / Further Reading: How to parse JSON in JavaScript

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化