【问题标题】:how to get result from json in jqueryjquery如何获取json的结果
【发布时间】:2018-04-07 15:51:57
【问题描述】:

我是 Javascript 和 Json 的新手
我需要在此 Jquery 中获得类似此示例的输出。
//我需要的结果示例:

sc.status(['4_3'], 'unavailable');
sc.status(['2_4'], 'unavailable');

和..

jQuery 代码:

setInterval(function() {
    $.ajax({
        type     : 'get',
        url      : 'test.php',
        dataType : 'json',
        success  : function(response) {
            //iterate through all bookings for our event 
            $.each(response.bookings, function(index, booking) {
                //find seat by id and set its status to unavailable
                sc.status(booking.seat_id, 'unavailable');
            });
        }
    });
}, 10000); //every 10 seconds

我使用 json_encode 将数据库值更改为 php 文件 (test.php) 中的 json 输出

php源码:

<?php

function checkrezerv() {
    $dbhost="localhost";
    $dbusername="root";
    $dbpassword="";
    $database="test";
    $databse_info = mysqli_connect( $dbhost,$dbusername,$dbpassword,$database );  
    $chreservednsql="SELECT seat_id FROM reserve_tbl WHERE reserved='1' AND show_id='1'";
    mysqli_set_charset($databse_info, "utf-8");
    mysqli_query($databse_info,"SET NAMES 'utf-8'");
    $row=mysqli_query($databse_info,$chreservednsql);
    if ($row->num_rows > 0) {
        $res=mysqli_fetch_array($row);
        echo json_encode($res);
    }
    else {
        $emptyc="";
        echo json_encode($emptyc);
    }
}
checkrezerv();
?> 

php 文件的结果在这里:

{"0":"1_5","seat_id":"1_5"}

我无法搜索和解决问题:(

【问题讨论】:

    标签: php jquery json ajax


    【解决方案1】:

    在服务器端你只得到第一行,改变 test.php 如下:

    if ($row->num_rows > 0) {
        $rows = array();
        while($res = mysqli_fetch_array($row)) $rows[] = $res;
        echo json_encode($rows);
    }
    else {
        $emptyc=array();
        echo json_encode($emptyc);
    }
    

    在js方面:

    $.ajax({
        type     : 'get',
        url      : 'test.php',
        dataType : 'json',
        success  : function(response) {
            //HERE
            $.each(response, function() {
                sc.status(this['seat_id'], 'unavailable');
            });
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-20
      • 2014-06-12
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      相关资源
      最近更新 更多