我正在使用变量 n
对 API 进行 Ajax JSON 调用。
变量越高,调用的结果就越多,具体取决于用户。
如果没有返回任何内容,则返回的 JSON 值 response
为“Nothing found”。
我正在尝试编写一个脚本,如果没有返回任何内容,则变量n
增加5并且代码循环直到收到包含结果的响应。
如何实现这一目标?
相关代码:
var n=5;
$.ajax({
type: 'GET',
dataType: 'jsonp',
jsonp: 'jsoncallback',
url: 'http://www.URL.com/API.php?var='+n,
success: function (data, status) {
$.each(data, function (i, item) {
//Do stuff here
});
}
});
响应示例:
if(item.response=="Nothing Found"){
n=n+5;
}
最佳答案
试试这个代码:
function sendRequest(n) {
$.ajax({
type: 'GET',
dataType: 'jsonp',
jsonp: 'jsoncallback',
url: 'http://www.URL.com/API.php?var='+n,
success: function (data, status) {
//i assume that your items have property response which you want to check
//if I'm wrong then it is just "if (data.response === ...)"
$.each(data, function (i, item) {
if (item.response === "Nothing found") {
sendRequest(n + 5);
};
else {
//process response
}
});
}
});
};
sendRequest(5);
关于php - 可更改的自定义 JSON Ajax 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16919026/