如何使此代码工作,问题是我似乎无法访问返回的数据,我知道它连接到服务器,但由于某种原因它不会工作,例如,我尝试提取标题,但没有出现。
$.ajax({
url : "https://www.googleapis.com/books/v1/volumes?q=harry+potter",
dataType : "jsonp",
async : true,
//if ajax call succeeds perform this action
success : function(result) {
ajax.parseJSONP(result);
},
//if there is an error to the ajax call perform this action
error : function(request, error) {
alert('Network error has occurred please try again!');
}
});
//parseJsonP and add new elements to list-view
var ajax = {
parseJSONP : function(result) {
//iterate each returned item
$.each(result, function(i, row) {
$('#listview_test').append('<li><h3>' + row.volumeInfo.title + '</h3></a></li>');
}); //end iteration of data returned from server and append to the list
$('#listview_test').listview('refresh'); // refresh the list-view so new elements are added to the DOM
}
}
我的困惑是在回调方法,在他们的例子书API有一个代码像显示下来,但我不得到它这部分q=harry+potter&callback=handleResponse
,我怎么能做到这一点,而使用$。ajax方法。试着理解所有的部分,但仍然很困惑?
<body>
<div id="content"></div>
<script>
function handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.text should have the HTML entities escaped.
document.getElementById("content").innerHTML += "<br>" + item.volumeInfo.title;
}
}
</script>
<script src="https://www.googleapis.com/books/v1/volumes?q=harry+potter&callback=handleResponse"></script>
</body>
尝试替换以下代码:
$.each(result, function(i, row) {
:
$.each(result.items, function(i, row) {
根据google示例代码,数据位于返回对象内的一个名为items
的数组中。