1

我是 jquery 编程的初学者:如果我的代码不好,我深表歉意。

我有一个简单的 html 文件

<!DOCTYPE html>
<html>
<head>
 <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

 <script>
$(document).ready(function() {
    var arr = [];
    var items = {};
    $.getJSON('testjson.json', function(data) {
        $.each(data, function(key, value){
            arr.push(value);
        });
        arr.join(',');
        items = {source: arr};
    });
    $("input#autocomplete").autocomplete(items);
  });
  </script>
</head>
<body style="font-size:62.5%;">

<div id="Heading" >
<h2 align="center">Client Browser</h2>
</div>  
<input id="autocomplete" size="100" align="middle"/>

</body>
</html>

这是我的 testjson.json 文件:

{
"1":"One",
"2":"Two",
"3":"Three"
}

当我使用 Altova XML spy 运行 html 文件时,我得到了正确的输出。但是当我在浏览器中打开它(通过 XAMP 服务器运行)时,这就是我在 Firefox 控制台中得到的:

jquery-ui.min.js 第 5 行中的“this.source 不是函数”

但是,如果我直接将 JS 对象传递给自动完成功能,它确实有效,例如,以下代码有效:

$("input#autocomplete").autocomplete({source:["One", "Two", "Three"]});

我无法理解问题出在哪里,因为项目包含相同的对象。我在这里做错了什么?

4

2 回答 2

2

我认为问题在于您不是在成功的 Ajax 请求之后而是在执行请求的同时初始化您的自动完成功能。

您应该将相应的行放在成功处理程序中:

$.getJSON('testjson.json', function(data) {
    $.each(data, function(key, value){
        arr.push(value);
    });
    arr.join(',');               // BTW, this line doesn't make any sense
    items = {source: arr};

    $("input#autocomplete").autocomplete(items);   // <-- place here
});
于 2012-06-13T22:37:59.937 回答
1

尝试移动这条线:

$("input#autocomplete").autocomplete(items);

进入您的 getJSON 回调。IE

$.getJSON('testjson.json', function(data) {
    $.each(data, function(key, value){
        arr.push(value);
    });
    arr.join(',');
    items = {source: arr};
    $("input#autocomplete").autocomplete(items);
});
于 2012-06-13T22:41:31.307 回答