可能重复:
如何返回 AJAX 响应文本?
我的 getJsonObject 函数有点问题。我希望我的代码做的是每次单击下一步时,getJsonObject 函数都会获取下一页的文章,并且当 dom 准备好时,我会显示文章的标题。但是如果出现错误(比如页面用完),那么 pageNr 将不再增加。问题是 getJsonObject 函数不返回 0,尽管 alert('return is 0)' 确实显示。
这是我的代码:
<html>
<head>
<title>World News</title>
<link rel="stylesheet" type="text/css" href="css/fullWindow.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<script src = "https://raw.github.com/janl/mustache.js/master/mustache.js" type = "text/javascript"></script>
<body>
<section id="mainContent">
<div class="prevNext floatRight"><a id="prev" href="#">prev</a> | <a id="next" href="#">next</a></div>
<section id="news">
<p id="headline">This is my headline for the moment.</p>
</section>
</section>
<script type="text/javascript">
$(document).ready(function(){
var pageNr = 1;
var sectionName = "science";
var err = '2';
$("#next").click(function(){
/* it removes the tag 'p' with id="headline" and inserts some other content */
$.when($('#headline').remove()).then(function(){
err = getJsonObject(sectionName, pageNr+1);
alert('err: '+err);
/* if there is no error go to the next page */
if(err == '0'){
pageNr++;
}
});
});
});
function getJsonObject(sectionName, pageNr){
$.getJSON('http://content.guardianapis.com/search?q=' + sectionName + '&page=' + pageNr + '&page-size=5&order-by=relevance&format=json&show-fields=all&date- id=date%2Flast7days&api-key=gd6ndfndjyr8sd2p3rq3ubkg&callback=?',
function(data){
var results;
/* I get status == error when I finish iterating the pages*/
if(data.response.status != 'error'){
$('#news').append('<p id="headline">'+data.response.results[pageNr].fields.headline+'</p>');
alert('return is 0');
return '0';
}else{
alert('return is 1');
return '1';
}
});
}
</script>
</body>
</html>
任何想法为什么 return 不起作用?谢谢。