2013-01-19 68 views
0

我需要調整以下代碼以對3個單獨的頁面進行多個請求(調整& page = & page = 2,& page = 3),除了重複3次,我該如何組合這個?Jquery JSON多個請求

$.getJSON("http://www.behance.net/v2/users/" + user + "/projects?api_key=" + api + "&callback=?&page=1", function (data) { 
    var project_str = ""; 
    for (i = 0; i < data.projects.length; i++) { 
     obj = {}; 
     obj = data.projects[i]; 
     project_str += '<a class="link" href="#' + obj.id + '"><img src="' + obj.covers['404'] + '" /></a>'; 
    } 
    $('#behance_container div').append(project_str); 
}); 
+0

似乎愚蠢暴露你的API密鑰...將是更聰明的將其存儲在服務器上,發送的網頁想服務器,並使其所有的請求,並返回所有網頁的一個JSON響應 – charlietfl

回答

0

喜歡的東西:

for(var i=1;i<=3;i++) 
{ 
    $.getJSON("http://www.behance.net/v2/users/" + user + "/projects?api_key=" + api + "&callback=?&page=" + i, function (data) { 
     var project_str = ""; 
     for (i = 0; i < data.projects.length; i++) { 
      obj = {}; 
      obj = data.projects[i]; 
      project_str += '<a class="link" href="#' + obj.id + '"><img src="' + obj.covers['404'] + '" /></a>'; 
     } 
     $('#behance_container div').append(project_str); 
    }); 
} 
0
$.each([1,2,3], function(i, numb) { 
    $.getJSON("http://www.behance.net/v2/users/"+user+"/projects?api_key="+api+"&callback=?&page="+numb, function (data) { 
     var project_str = ""; 
     $.each(data.projects, function(i, obj) { 
      project_str += '<a class="link" href="#' + obj.id + '"><img src="' + obj.covers['404'] + '" /></a>'; 
     }); 
     $('#behance_container div').append(project_str); 
    }); 
}); 
0

因爲$.getJSON調用是異步,您可能希望它顯示給用戶之前,先收集所有數據。否則,每次數據檢索/附加到DOM時,您都會得到一個「閃光燈」。以下是未經測試的,但應該工作(如果沒有,我希望你在正確的方向上幫助你)。

var nrOfPages = 3, 
    projects = []; 

for(var i = 1; i <= nrOfPages; i++) { 
    retrieveData(i); 
} 

// Retrieve the data by the pageNr 
function retrieveData(pageNr) { 
    $.getJSON("http://www.behance.net/v2/users/" + user + "/projects?api_key=" + api + "&callback=?&page=" + pageNr, function (data) { 
     for (i = 0; i < data.projects.length; i++) { 
      projects.push(data.projects[i]); 
     }; 

     if(pageNr == nrOfPages) { // Check if all the pages are retrieved 
      processData(); 
     } 
    }); 
}; 

// Process the retrieved data 
function processData() { 
    var project_str = ""; 
    for (i = 0; i < data.projects.length; i++) { 
     obj = {}; 
     obj = data.projects[i]; 
     project_str += '<a class="link" href="#' + obj.id + '"><img src="' + obj.covers['404'] + '" /></a>'; 
    } 
    $('#behance_container div').append(project_str); 
};