while循环请求JSON

时间:2014-05-28 09:10:52

标签: javascript json

我一直在尝试做一些我认为非常简单的事情,但现在我很确定我已经很好地过度简化了它,或者只是把我的循环搞砸了一些基本的东西。我试图搜索包含JSON对象的链接列表,以查找包含特定数据的特定链接。

我看到的JSON链接看起来像这样:

链接1:

{"genre": "fantasy", "title": "Book 1"}

链接2:

{"genre": "scifi", "title": "Book 2"}

我的循环的目标是找到一本带有流派' scifi'但我当前的代码只会导致或什么也不会发生。如果有人能发现我做错了什么,请告诉我。如果不是很明显,我在这方面很新,所以任何建议都会非常受欢迎。

function find_book(){ // called by button onclick
    var i = curr_line+1 // current line's default value is 0
    var x = 0;
    var limit = bookcount-1; //bookcount is total number of books

    while(x != 1) {
        request= new XMLHttpRequest();
        request.open("GET","http://example.com/books/?book="+i,true);                    
        request.onreadystatechange=function() {
            if(request.readyState==4 && request.status==200) {
                var jsonbook = JSON.parse(request.responseText);
                alert('genre is'+jsonbook.genre);
            }
        }
        request.send()

        if(jsonbook.genre == "scifi"){
            alert('book is at '+i);
            x=1;
        }
        if(i>limit){
            alert('end of book list');
            x=1;
        }

        i++;
    }
}

2 个答案:

答案 0 :(得分:1)

JSON书超出了范围。此外,ajax调用是异步发生的(即aj中的a)尝试调用直接函数recursivley。某事。像:

function check_book(bookID, limit) {
    request = new XMLHttpRequest();
    request.open("GET", "http://example.com/books/?book=" + bookID, true);
    request.onreadystatechange = function () {
        if (request.readyState == 4 && request.status == 200) {
            var jsonbook = JSON.parse(request.responseText);
            alert('genre is' + jsonbook.genre);
            if (jsonbook.genre == "scifi") {
                alert('book is at ' + bookID);
                return;
            } else if (bookID > limit) {
                alert('end of book list');
                return,
            } else {
                bookID++;
                check_book(bookID, limit)
            }
        }
    }
    request.send()
}

function find_book(){ // called by button onclick
    var i = curr_line+1 // current line's default value is 0
    var limit = bookcount-1; //bookcount is total number of books

    check_book(i, limit);
}

答案 1 :(得分:-1)

首先观察。尝试在alert('genre is'+jsonbook.genre);行下移动以下代码。

if(jsonbook.genre == "scifi"){
 alert('book is at '+i);
 x=1;
 }

if(i>limit){
alert('end of book list');
x=1;
}

它应该如下所示,因为一旦返回调用是异步的,你必须用你的逻辑处理jsonobject

   if(request.readyState==4 && request.status==200)
    {

       var jsonbook = JSON.parse(request.responseText);
       alert('genre is'+jsonbook.genre);
       if(jsonbook.genre == "scifi"){
         alert('book is at '+i);
         x=1;
       }

       if(i>limit){
           alert('end of book list');
            x=1;
       }
    }