【问题标题】:jQuery Autocomplete using Ajax won't parse使用 Ajax 的 jQuery 自动完成不会解析
【发布时间】:2014-06-11 15:52:26
【问题描述】:

我正在尝试使用带有 ajax 的基本自动完成功能。我无法理解结果。我对 jQuery 比较陌生,所以我为我的语法道歉,我更擅长 PHP。

$("#category_title").autocomplete({
  source: function (request, response) {
    $.ajax({
       url: 'index.php?controller=AdminEvents&action=AutoComplete&variable=asdf',
       type: 'GET',
       success: function(data){
         response(data);
       }
    });
  },
  minLength: 2
});

控制器的响应是样本数据,实际上还没有从数据库中得到任何东西:

if ($this->isXHR())
{
  //$response = "{value1:test, value2:test2}";
  $response['value1'] = "test";
  $response['value2'] = "test2";
  $json = json_encode($response);
  print($json);
}

这是我觉得奇怪的部分.. 基本上,这是可行的,并且会弹出自动完成框,但这是它对返回的作用:

为什么?

感谢您的宝贵时间!

【问题讨论】:

    标签: jquery ajax autocomplete


    【解决方案1】:

    试试这个:

    jQuery

    $(document).ready(function(){
        $('#zipsearch').autocomplete({source:'suggest_zip.php', minLength:2});
    });
    

    PHP

    $response = array();
    $response[0]=array('label'=>'test','value'=>'test');
    $response[1]=array('label'=>'test2','value'=>'test2');
    echo json_encode($response);
    

    【讨论】:

    • 同样的结果。
    • 这是一个例子,检查一下,它有效。 htmlblog.us/jquery-autocomplete
    • 看,我试图采用我认为你想说的内容,我没有兴趣替换我为“解决它”而写的所有内容。我想弄清楚哪里出了问题,这样我才能理解。
    【解决方案2】:

    这可能对你有帮助

    jquery

    $("#zipsearch").autocomplete({
                        source: function(req,res) {
                            $.ajax({
                                url: "index.php?controller=AdminEvents&action=AutoComplete&variable=asdf",
                                dataType: "json",
                                type: "GET",
                                data: {
                                    term: req.term
                                },
                                success: function(data) {
                                    res($.map(data, function(item) {
                                        return {
                                            label: item.value1,
                                            value: item.value1
                                        };
                                    }));
                                },
                                error: function(xhr) {
                                    alert(xhr.status + ' : ' + xhr.statusText);
                                }
                            });
                        }
                    });
    

    PHP

    <?php
    $response=array();
    $response[0]['value1'] = "test";
    $response[1]['value1'] = "test2";
    print json_encode($response);
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 2011-06-29
      • 1970-01-01
      相关资源
      最近更新 更多