这是我的代码整洁干净
你可以看到我做了一个for循环并将一个[i]变量传递给了api 现在发生的事情是循环是没有击中api并回到循环。任何解决方案?
var a = ['a1','a2','a3','a4','a5','a6','a7','a8','a9','a10','a11','a12','a13','a14','a15','a16','a17','a18','a19','a20','a21','a22','a23','a24','a25','a26','a27','a28','a29','a30','a31','a32','a33','a34','a35','a36', 'a37']
console.log(a)
for(var i = 0; i <= a.length; i++){
$http({
url: '/MyApp/getIt?urlofpage=https://www.example.com/alpha/'+a[i]+'.html',
method: "POST",
}).success(function(response){
console.log(a[i]);
console.log(response);
});
}
答案 0 :(得分:1)
看起来你正在尝试使用jQuery ajax来调用API。
如果是这种情况,您应该使用$.post
或$.ajax
:
var a = ['a1','a2','a3','a4', ...];
console.log(a);
for(var i = 0; i <= a.length; i++){
$.ajax({
url: '/MyApp/getIt?urlofpage=https://www.example.com/alpha/'+a[i]+'.html',
method: "POST",
success: function(response) {
console.log(a[i]);
console.log(response);
}
});
}
否则,请分享$http
功能。
答案 1 :(得分:0)
您不能将for循环用于数据库调用,因为它是异步的。请查看以下代码。
var a = ['a1','a2','a3','a4', ...];
var i=0;
checkArrayLength();
function checkArrayLength(){
if(i<a.length){
makeRequest(a[i]);
}
}
function makeRequest(param1){
$.ajax({
url: '/MyApp/getIt?urlofpage=https://www.example.com/alpha/'+param1+'.html',
method: "POST",
success: function(response) {
console.log(a[i]);
i=i+1;
console.log(response);
checkArrayLength();
},
error:function(response) {
console.log(a[i]);
i=i+1;
console.log(response);
checkArrayLength();
}
});
}