2011-12-19 19 views
0

jQuery get()関数を使用してHTTP GETリクエストを作成しようとしていますが、何か問題があります。ここでjQueryからGETリクエストを作成する際の問題

は私のコードは次のようになります。

// get the links on the page 
var pageLinks = $.find('#pageLinks'); 
// loop through each of the links 
$(pageLinks).find('a').each(function(){ 
    if($(this).attr('title') !== "Next Page"){ 
     // make a GET request to the URL of this link 
    $.get($(this).attr("href"), function(data) { 
      console.log("here"); 
      var temp = parse_page(data); 
      // concatenate the return string with another 
      bdy = bdy+String(temp); 
      console.log("done"); 
     }); 
    } 
}); 

私はからデータを取得する必要があり、複数のページがあります。 get()関数は非同期なので、ページはランダムな順序で取得されます。第二に、連結は機能しません。私はそれぞれのページを入手しても、bdyには入れません。

誰も私がこれに対処する方法を提案することはできますか?

ありがとうございます!

+0

'String(temp)'とは何ですか? –

+0

'bdy'はどこに定義されていますか? – muratgu

+0

同期に関する問題が発生する限り、jQueryの延期を使用してコールバックをチェーン化してみませんか? – JesseBuesking

答えて

0

JSで制御フローを管理できるモジュールがあることがわかりました。私が見つけたものは以下のとおりです。上記のモジュールを使用してヘルプについて

、私のフォローアップの質問hereを参照してください。

0

すべてのページが取得された後に、つまりgetという結果が辞書または配列に格納された後に、bdyを作成します。すべてのgetが完了するのを待ちます。それらを正しい順序で組み立てます。

+0

私はそれについて考えましたが、これを行うための組み込みの方法があるはずです。これは私がここで見つけたいと思っているものです – efficiencyIsBliss

0

私はこの1つを試してみましたが、それが動作します:

var results = []; 
var count = 0; 

function allDone() { 
    var bdy = results.join(""); 
    // do stuff with bdy 
} 

// get the links on the page 
var pageLinks = $.find('#pageLinks'); 

// filter the links so we're left with the links we want 
var wantedLinks = $(pageLinks).find('a').filter(function (idx) { 
    return $(this).attr('title') !== "Next Page"; 
}); 

// remember how many links we're working on 
count = wantedLinks.length; 

// loop through each of the links 
wantedLinks.each(function (idx) { 
    // make a GET request to the URL of this link 
    $.get($(this).attr("href"), function (data) { 
     console.log("here"); 
     var temp = parse_page(data); 
     results[idx] = temp; 

     // Decrement the count. 
     count--; 

     if (count === 0) { 
      // All done. 
      allDone(); 
     } 
    }); 
}); 

をあなたが実行できるデータ型に、これをさらに行くと抽象的な可能性:@muratguが言ったことの一例として、

// get the links on the page 
var pageLinks = $('a'); 
var bdy 
// loop through each of the links 
$(pageLinks).each(function(){ 
console.log(this); 
     // make a GET request to the URL of this link 
      $.get($(this).attr("href"), function(data) { 

      // concatenate the return string with another 
      bdy = bdy + data.toString(); 
      console.log(bdy); 
     }); 

}); 
+0

私は前にこのコードを使って同じ結果を得ています。 – efficiencyIsBliss

0

N非同期ダウンロードが完了したら、あなたに通知します。

関連する問題