【问题标题】:jQuery autocomplete cross site domain - listbox does not displayjQuery自动完成跨站点域 - 列表框不显示
【发布时间】:2018-04-17 14:20:12
【问题描述】:

我想对外部数据使用自动完成功能。我按照手册和数据顺利返回,但列表框不显示。有人可以帮帮我吗?

这是我的 js:

$('.hledejNACE').autocomplete({
    source: function( request, response ) {
        $.ajax({
            url: "ac.php",
            dataType: "jsonp",
            data: {term: request.term},
            success: function( data ) { response( data ); }
        });  
    },
    minLength:1,
    select:function(evt, ui) {
        // when a name is selected, populate related fields in this form
        this.form.kodNACE.value = ui.item.kodNACE;
    }
}); 

Mozilla 开发工具说,数据以 JSON 格式成功返回。

这是我的html:

<form onsubmit="return false;">
    Name: <input id="hledejNACE" type="text" class="hledejNACE" style="width:250px;"/>
    Code: <input id="kodNACE" type="text" disabled />
</form>

我已经链接了这些脚本:

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

【问题讨论】:

  • 如果你能给我链接到你的测试服务器,也许我可以帮助你。它返回 jsonjsonp?
  • 可以在 Chrome、Opera 和 Internet Explorer 上运行
  • 但是我没有看到返回值的列表框...
  • 嗯......它适用于所有东西,但不适用于 FireFox......这很奇怪
  • jQuery 中似乎有错误... SyntaxError: '*,:x' is not a valid selector in jquery-1.10.2.js line 1639...

标签: php jquery json autocomplete cross-domain


【解决方案1】:

嗯,我找到了解决办法:

您需要在 PHP json 返回中使用回调:

<?php

    $data = '{}'; // json string

    if(array_key_exists('callback', $_GET)){

        header('Content-Type: text/javascript; charset=utf8');
        header('Access-Control-Allow-Origin: http://www.example.com/');
        header('Access-Control-Max-Age: 3628800');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

        $callback = $_GET['callback'];
        echo $callback.'('.$data.');';

    }else{
        // normal JSON string
        header('Content-Type: application/json; charset=utf8');

        echo $data;
    }
?>

感谢大家的努力!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-20
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 1970-01-01
    • 2011-05-07
    • 2019-02-18
    相关资源
    最近更新 更多