更改的自定义JSON Ajax循环


Custom JSON Ajax loop that changes

我正在使用变量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);