2010-01-27 66 views
1

我试图在使用jQuery和自动完成插件的照片网站上实现实时搜索。当我在本地指定数据时,一切正常:通过AJAX将多维JSON数组传递给jQuery自动完成的帮助

var data = [ {text:'Link A', url:'/page1'}, {text:'Link B', url: '/page2'} ]; 

但是,当我将它移动到PHP时,jQuery无法正确解析结果。我真的不确定这里发生了什么事。我当前的代码如下:

<script> 
$(document).ready(function(){ 
var data = '/livesearch'; 
$("#aut_field").autocomplete(data, { 
    formatItem: function(item) { 
    return item.text; 
    } 
}).result(function(event, item) { 
    location.href = item.url; 
}); 
       }); 
</script> 

而且我的PHP脚本按以下格式打印多维数组:

{"1":{"text":"Google Website","url":"http:\/\/www.google.com"}, 
"2":{"text":"Yahoo Website","url":"http:\/\/yahoo.com"},} 

但是当我做警报(item.text)变量未定义说。

如果我确实警告(item),我会看到PHP输出的整个字符串。

我试着玩弄eval(),但我不知道把它放在哪里或如何让JS实际解释数据。谢谢你的帮助。示例代码特定于我的实现感谢。

+1

什么是在第一代码片段{ldelim}和{} rdelim? – 2010-01-27 07:12:25

+0

对不起 - 应该阅读{和} ......它是从Smarty复制粘贴的。固定。 – ensnare 2010-01-27 07:22:34

回答

1

问题出在php代码上。

你的工作是模仿工作JavaScript数组的strcuture。见PHP的json_encode()

1

尝试在你的PHP这种模式:

[ 
    {"text":"Google Website","url":"http:\/\/www.google.com"}, 
    {"text":"Yahoo Website","url":"http:\/\/yahoo.com"} 
] 
+0

工作。谢谢。 – ensnare 2010-01-27 18:59:59

+0

然后你应该通过点击空白检查来接受这个答案。 – SLaks 2010-01-28 02:00:26

0

而且你的PHP脚本返回一个多维数组/ 对象组合。 如果你坚持(你吹你的变种有几个 “文本:” AMD “URL;”)它shou1ld是:

[[{"text":"Google Website","url":"http:\/\/www.google.com"}],[{"text":"Yahoo Website","url":"http:\/\/yahoo.com"}]] 

更好:

var x=[["Google Website","http:\/\/www.google.com"],["Yahoo Website","http:\/\/yahoo.com"]]; 

如果你要跳转到雅虎网站:var url = x [1] [1];

或者:

var x={"Google_Website":"http:\/\/www.google.com","Yahoo_Website":"http:\/\/yahoo.com"}; 

如果你想跳到Google_Website:VAR URL =×〔 “Google_Website”];

我的技巧:登陆enter link description here