0

我在 for 循环中调用 getjson。目前我的代码打印了所有的物品并没有省略不出售的物品!

这是检查商品是否在售的部分:

 $.getJSON('http://anyorigin.com/get?url=http://www.asite.com/itemtocheck.php='+ itemName + '/&callback=?', function(data){

       var siteContents = data.contents;      
     var n=siteContents.search("This item is not on sale");

    if(n=-1)
        {
         //alert("This item is on sale. n:"+n);

         var siteContents2 = "This item is on sale:"+itemName;
         document.getElementById("myDiv").innerHTML += siteContents2;
        };

我不知道这个 if 语句有什么问题,即使该物品不出售,它也总是成真!有没有办法在“for循环”内每次调用getjson之间延迟(非常短的延迟,所以getjson获取数据并有足够的时间过滤它)?

我不确定,但我认为也许“for循环”调用getjson太快了,没有给每个项目足够的时间来检查。我什至尝试这样做:

setTimeout(GetJSONResult('pen'), 500);

但由于某种原因它没有工作!任何人都可以帮助修复我的代码,以便过滤掉不出售的商品吗?谢谢

    <script>  

function GetJSONResult(itemName)
{
//alert("test:"+itemName);
 $.getJSON('http://anyorigin.com/get?url=http://www.asite.com/itemtocheck.php='+ itemName + '/&callback=?', function(data){

       var siteContents = data.contents;      
  //writes to textarea  
  document.myform.outputtext.value = siteContents ;  


var n=siteContents.search("This item is not on sale");

document.write("value of n"+n);
 if(n=-1)
{
 //alert("This item is on sale. n:"+n);

 var siteContents2 = "This item is on sale:"+itemName;
 document.getElementById("myDiv").innerHTML += siteContents2;
}; 
});  

};


items=["pen","paper","book","tshirt","cup","coffee","plate","cherry","apple","mango","orange"];
for (var i=0;i<items.length;i++)
{
document.write(items[i] + "<br>");

GetJSONResult(items[i]);
}
////setTimeout(GetJSONResult('pen'), 500);
////setTimeout(GetJSONResult('paper'), 500);
////setTimeout(GetJSONResult('book'), 500);
////setTimeout(GetJSONResult('tshirt'), 500);

////GetJSONResult('cup');
////GetJSONResult('coffee');
////GetJSONResult('plate');
////GetJSONResult('cherry');
////GetJSONResult('apple');
////GetJSONResult('mango');
////GetJSONResult('orange');

</script>   
</head>

<body>
<br>

  <div id="myDiv"></div>
  <br>  


</body>
</html>
4

1 回答 1

1

您是否注意到在您的 if 语句中您正在执行作业?

如果(n=-1)

应该是

如果(n == -1)

或者如果你想真正安全

如果(n === -1)

于 2013-05-09T14:35:06.693 回答