【问题标题】:Why is this JSON not working?为什么这个 JSON 不起作用?
【发布时间】:2013-03-25 10:23:09
【问题描述】:

我想通过 select2 插件使用 MySQL 远程数据作为标签。但是我对 JSON 的学习曲线非常薄弱。请帮我纠正这种 JSON 格式。

$("#e7").select2({
    placeholder: "Search for a movie",
    minimumInputLength: 3,
    ajax: {
        url: "search.php",
        dataType: 'jsonp',
        quietMillis: 100,
        data: function (term, page) { // page is the one-based page number tracked by Select2
            return {
                q: term, //search term
                page_limit: 10, // page size
                page: page, // page number
                apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
            };
        },
        results: function (data, page) {
            var more = (page * 10) < data.total; // whether or not there are more results available

            // notice we return the value of more so Select2 knows if more results can be loaded
            return {
                results: data.movies,
                more: more
            };
        }
    },
    formatResult: movieFormatResult, // omitted for brevity, see the source of this page
    formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page
    dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    escapeMarkup: function (m) {
        return m;
    } // we do not want to escape markup since we are displaying html in results
});

这里是search.php

<?php
    $sql=mysqli_query($db3->connection,"SELECT * FROM tags");

    while($row=mysqli_fetch_array($sql)){
        $tags=$row['tags'];
        $id=$row['id'];

        $response=array();
        $response['tags']=$tags;
        $response['id']=$id;     
    }

    echo json_encode($response);
?>

【问题讨论】:

  • 如果您不解释问题是什么,即您期望发生什么、实际发生什么、您收到什么错误消息等,那么我们不太可能提供帮助你。请编辑您的问题并详细说明问题。不,“它不工作”不是一个有用的错误描述。我的烤面包机也不工作。
  • 您在 while 循环中重置 $response。将$response=array(); 移到外面并用$response[]=array('tags'=&gt;$tags, 'id'=&gt;$id); 替换里面

标签: php jquery json jquery-select2


【解决方案1】:

您的 while 循环未填充 $response 数组。 $响应=数组();每次循环迭代都会重置 $response

$sql=mysqli_query($db3->connection,"SELECT * FROM tags");

$response=array();
while($row=mysqli_fetch_array($sql)){
    $tags=$row['tags'];
    $id=$row['id'];

    $response[]=array('tags'=>$tags, 'id'=>$id);

}

echo json_encode($response);

【讨论】:

    猜你喜欢
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2013-03-10
    • 1970-01-01
    • 2014-01-01
    • 2013-11-14
    相关资源
    最近更新 更多