dounanyin3179 2016-06-27 17:03
浏览 84

如何利用JQuery AJAX请求的JSON响应? [重复]

This question already has an answer here:

I am using PHP and MySQL to swap out some content. A click handler sends an AJAX request to the PHP script which performs a query, then encodes and prints the result as a JSON object.

All that seems to work, but I seem to be stuck on the most silly thing: I can't work out how to actually use the result, as in set the individual values to JavaScript variables.

Edit: I added a couple more things I tried, to get a specific value to print out to the console, no luck thus far.

Edit: Found the correct syntax:

response[0].foo

javascript:

var listId = $(this).children('.hidden-id').html();

        var options = new Object();
        options.data = listId;
        options.dataType = 'json';
        options.type = 'POST';

        options.success = function(response) {
            console.log(response[0].foo);
        };

        options.url = './inc/change_list.php';

        $.ajax(options);

the PHP script:

$list_id = $_POST['list_id'];
    $q = "SELECT id, title, description, position FROM items WHERE list_id=$list_id ORDER BY position ASC";
    $r = mysqli_query($dbc, $q);
    if (mysqli_num_rows($r) > 0) {

        $result = array();
        while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
            $add_result = [
                'id' => $row['id'],
                'title' => $row['title'],
                'description' => $row['description']
            ];
            $result[] = $add_result;
        }
        $result = json_encode($result);
        echo $result;

    } else {
        echo '{"result":"failure"}';
    }
</div>
  • 写回答

1条回答 默认 最新

  • dongxiegao3071 2016-06-27 17:05
    关注

    The JSON response will automatically be parsed to a Javascript object. So you can just do:

    options.success = function(response) {
        console.log(response.foo); // logs "bar"
        // or
        var foo = response.foo; // foo now holds "bar" as it's value
    };
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!