我正在尝试使用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)时,变量显示为undefined。
如果我发出警告(item),我会看到PHP输出的整个字符串。
我尝试使用eval(),但我不知道在哪里放或者如何让JS实际解释数据。谢谢你的帮助。我非常感谢特定于我的实现的示例代码。
答案 0 :(得分:1)
问题在于PHP代码。
你的工作是模仿工作javascript数组的结构。请参阅php的json_encode()
答案 1 :(得分:1)
在你的php中尝试这种模式:
[
{"text":"Google Website","url":"http:\/\/www.google.com"},
{"text":"Yahoo Website","url":"http:\/\/yahoo.com"}
]
答案 2 :(得分:0)
您的PHP脚本返回多维数组/ 对象混合。 如果你坚持(你用几个“text:”amd“url;”炸掉你的var),那么它应该是:
[[{"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 = x [“Google_Website”];
我的提示:访问enter link description here