【问题标题】:PHP array as JSON response for jQuery autocompletePHP数组作为jQuery自动完成的JSON响应
【发布时间】:2016-01-18 13:40:38
【问题描述】:

我有一个搜索表单,我想在输入 3 个字符时通过 jQuery 自动完成显示建议。这些建议来自 mySQL DB。 会发生什么:jQuery 确实成功地将键入的字符传输到 PHP 文件,在那里它们成功地嵌入到 mySQL 查询中。 当我使用假定的搜索词 f.e. 单独打开 PHP 文件时。像这样:/soplogsearch.php?term=xyz 它工作得很好,我看到了echo json_encode($return_arr); 的目标结果 但回到 HTML 搜索表单文件自动完成并没有任何建议。我在控制台中没有错误。我试图在 HTML 文件的其他地方回显 json_encode,它的输出是 Null

我为(非常简单的)Javascript/jQuery 和 HTML 设置做了一个小提琴:https://jsfiddle.net/9bf6s07f/1/

相关的 PHP 代码如下所示:

if (isset($_GET['term']))
    {
    $term = $_GET['term'];
    $termwild = "%$term%";
    $return_arr = array();
    $service = mysql_query("SELECT DISTINCT service FROM master WHERE service LIKE \"" . $termwild . "\"");
    while ($data = mysql_fetch_array($service))
        {
        $return_arr[] = $data[0];
        }
    json_encode($return_arr);
    echo json_encode($return_arr);
    }

编辑:为了更快地访问,我在这里包含代码的 HTML 和 jQuery 部分,而不是链接到小提琴 https://jsfiddle.net/9bf6s07f

<body>
     <label>Service:</label>
     <input type='text' name='' value='' class='auto'>
</body>

和 jQuery:

$(document).ready(function() {
  $(function() {
    $(".auto").autocomplete({
      source: "soplogsave.php",
      minLength: 3
    });
  });
});

有人知道我做错了什么吗?我用一组 javascript 变量分别测试了自动完成功能,效果很好。

编辑 2:因为所有 cmets 似乎都暗示我的 PHP 是错误的,并且我会在控制台中出现错误,所以我从控制台的网络选项卡中截取了屏幕截图:http://i.imgur.com/i6nAQ98.png

【问题讨论】:

  • 我认为您的查询不正确。试试这个:$service = mysql_query("SELECT DISTINCT service FROM master WHERE service LIKE '%{$term}%'"); 我正在我的应用程序中做与您尝试做的类似的事情。
  • 你的PHP文件返回结果了吗?
  • 但是这个查询似乎确实有效!我可以用 mysql_fetch_array 完美地回应它
  • 只有 json 数据,你不应该回显任何 HTML,只需让你的数据库在幕后工作,然后 header('Content-Type: application/json'); 然后:echo json_encode($return_arr);。没有魔法,jQuery(任何框架都没有)无法知道您在随机 HTML 文件中隐藏了一些 json。
  • 您可以使用另一个 php 文件或路由,具体取决于您的项目。什么都没有,只有 json。再见;-)。

标签: javascript php jquery mysql json


【解决方案1】:

这就是我在代码中实现它的方式:

PHP

$param = $_GET["term"];

$stk_adddep = "
SELECT * FROM stocktake_products WHERE stocktake_id = '{$stocktake_id}' AND is_deli = 0 AND (product_code LIKE '%{$param}%' OR product_name LIKE '%{$param}%'); ";

//FB::info($stk_adddep);
//echo $stk_adddep;
//die();
$result = db::c()->query($stk_adddep);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {

    $row_array['itemCode']  = $row['product_code'];
    $row_array['itemDesc']  = $row['product_name'];
    //$row_array['itemPrice'] = $row['unit_cost_price'];

    array_push( $return_arr, $row_array );
}

/* Free connection resources. */
//mysql_close($conn);

/* Toss back results as json encoded array. */
echo json_encode($return_arr);

然后是javascript

$(document).ready(function(){
// Use the .autocomplete() method to compile the list based on input from user
var url10 = '<?php echo Navigation::gUrl('/users/admin/stocktake_details_cocktails.php', array('stocktake_id' => $stocktake_id, 'action' => 'find_products'));?>';

$('#itemCode').autocomplete({
    source: url10,
    minLength: 1,
    select: function(event, ui) {
        var $itemrow = $(this).closest('tr');
                // Populate the input fields from the returned values
                $itemrow.find('#itemCode').val(ui.item.itemCode);
                $itemrow.find('#itemDesc').val(ui.item.itemDesc);
                //$itemrow.find('#itemPrice').val(ui.item.itemPrice);

                // Give focus to the next input field to recieve input from user
                $('#itemQty').focus();

        return false;
    }
// Format the list menu output of the autocomplete
}).data( "autocomplete" )._renderItem = function( ul, item ) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + item.itemCode + " - " + item.itemDesc + "</a>" )
        .appendTo( ul );
};

看看你是否可以将它应用到你的代码中?

【讨论】:

  • 谢谢,但这对于我的简单代码来说太广泛了 :( 我对 javascript 不太了解
【解决方案2】:

答案由用户@n00dl3 发布在 cmets 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多