我使用http://netflixroulette.net/api/根据文本框中的类型提取信息,但是我无法获取对象参数的值。
$('.moviebutton').on('click', function(e){
e.preventDefault();
var title = $('#moviename').val();
var movieresults = $('#movieresults');
var requestURL = '//netflixroulette.net/api/api.php';
$.getJSON(requestURL, {
'title' : title,
}, function(data) {
console.log(data);
if(data){
myMovie = '<table>';
myMovie += '<tr><th>Rating</th><th>Title</th><th>Poster Link</th></tr>';
$.each(data, function(i, rep){
myMovie += '<tr>';
myMovie += '<td>';
myMovie += rep.rating;
myMovie += '</td>';
myMovie += '<td>';
myMovie += rep.show_title;
myMovie += '</td>';
myMovie += '<td>';
myMovie += rep.poster;
myMovie += '</td>';
myMovie += '</tr>';
});
myMovie += '</table>';
} else {
myMovie = '<p>Sorry no address where found</p>';
}
movieresults.html(myMovie);
});
});
返回的是
Object {unit: 883, show_id: 70299043, show_title: "Attack on Titan", release_year: "2013", rating: "4.6"…}
category:"Anime"
director:""
mediatype:1
poster:"http://netflixroulette.net/api/posters/70299043.jpg"
rating:"4.6"
release_year:"2013"
runtime:"24 min"
show_cast:"Yuki Kaji, Yui Ishikawa, Marina Inoue, Daisuke Ono, Hiro Shimono, Hiroshi Kamiya, Keiji Fujiwara, Kishô Taniyama, Romi Park, Ryota Ohsaka"
show_id:70299043
show_title:"Attack on Titan"
summary:"For over a century, people have been living behind barricades to block out the giant Titans that threaten to destroy the human race. When a Titan destroys his hometown, young Eren Yeager becomes determined to fight back."
unit:883
__proto__:Object
但是,当我尝试rep.rating或rep.show_title时,我得到了未定义的,我是否错过了一个参数或者不是rep.w / e我会使用object.rating吗?
答案 0 :(得分:1)
由于此处的返回值实际上是一个对象,因此您只需使用data.rating
而不是使用循环并调用rep.rating
,如:
$.getJSON(requestURL, {
'title': title,
}, function(data) {
console.log(data);
if (data) {
myMovie = '<table>';
myMovie += '<tr><th>Rating</th><th>Title</th><th>Poster Link</th></tr>';
myMovie += '<tr>';
myMovie += '<td>';
myMovie += data.rating;
myMovie += '</td>';
myMovie += '<td>';
myMovie += data.show_title;
myMovie += '</td>';
myMovie += '<td>';
myMovie += data.poster;
myMovie += '</td>';
myMovie += '</tr>';
myMovie += '</table>';
} else {
myMovie = '<p>Sorry no address where found</p>';
}
movieresults.html(myMovie);
});
简单演示:
var movieresults = $('#movieresults');
var requestURL = 'http://netflixroulette.net/api/api.php?title=Attack%20on%20titan';
$.getJSON(requestURL, function(data) {
console.log(data);
if (data) {
myMovie = '<table>';
myMovie += '<tr><th>Rating</th><th>Title</th><th>Poster Link</th></tr>';
myMovie += '<tr>';
myMovie += '<td>';
myMovie += data.rating;
myMovie += '</td>';
myMovie += '<td>';
myMovie += data.show_title;
myMovie += '</td>';
myMovie += '<td>';
myMovie += data.poster;
myMovie += '</td>';
myMovie += '</tr>';
myMovie += '</table>';
} else {
myMovie = '<p>Sorry no address where found</p>';
}
movieresults.html(myMovie);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<p id="movieresults"></p>
&#13;