【发布时间】:2011-08-20 20:07:00
【问题描述】:
我正在使用 Codeigniter 并尝试使用 jQuery 自动完成功能。我还在为 Codeigniter 使用 @Phil Sturgeon 客户端休息库,因为我正在从 netflix 获取自动完成数据。我返回了正确的 JSON,我可以使用
访问第一个元素response(data.autocomplete.autocomplete_item[0].title.short);
但是当我遍历结果时
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short)
}
它就像一个字符串。假设结果是“浪荡公子”,它将返回:
Object.value = s
Object.value = w
Object.value = i
等等。
js:
$("#movies").autocomplete({
source: function(request, response) {
$.ajax({
url: "<?php echo site_url();?>/welcome/search",
dataType: "JSON",
type:"POST",
data: {
q: request.term
},
success: function(data) {
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
}
});
}
}).data("autocomplete")._renderItem = function(ul, item) {
//console.log(item);
$(ul).attr('id', 'search-autocomplete');
return $("<li class=\""+item.type+"\"></li>").data( "item.autocomplete", item ).append("<a href=\""+item.url+"\">"+item.title+"</a>").appendTo(ul);
};
控制器:
public function search(){
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// set var equal to results
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'));
//$this->rest->debug();
//$json_data = $this->load->view('nice',$data,true);
//return $json_data;
echo json_encode($netflix_query);
}
json 返回
{"autocomplete":
{"autocomplete_item":[
{"title":{"short":"The Strawberry Shortcake Movie: Sky's the Limit"}},
{"title":{"short":"Futurama the Movie: Bender's Big Score"}},
{"title":{"short":"Daffy Duck's Movie: Fantastic Island"}}
...
有什么想法吗? 谢谢。
有一些控制台日志带有返回
the url
【问题讨论】:
-
还发布一些您收到的 json 响应
-
当 netflix 已经返回 json 时,为什么还要执行 json_encode?我不熟悉 netflix api,但从我在你的问题中看到的。这对我来说似乎很奇怪。也许你应该只传递 netflix 响应,因为它已经输出为 json?
-
@Ivan Ivanić i json_encode 响应,因为如果我只是回显响应或只是返回它,那么我会收到一个 php 错误,即 Object 无法转换为字符串。将编辑问题以显示 json 返回
标签: php json codeigniter jquery