2010-08-27 65 views
0

我已經構建了JS類/ jQuery的:在jQuery中,如何在其他類方法中使用返回的JSON對象?

function JSONRequest(request_id, type){ 
    this.request_id = request_id; 
    JSONsvc ='json_dispatch.php'; 
    this.type = type; 
} 

JSONRequest.prototype.query = function() { 
    $.getJSON(JSONsvc, 
      {request_id:this.request_id, type:this.type}, 
      function(data) { 
       return data; 
      }   
    ); 
} 
JSONRequest.prototype.buildKeyValues = function(data) { 
    $.each(data.items, function(i,item){ 
     //$('textarea').text(item.comment); //hack 
     $.each(item, function(j,key){ 
      $("#"+j).val(key); 
     }) 
    }) 
} 

JSONRequest.prototype.buildTableRows = function(data) { 
    var tbodyContainer; 
    tblRows = ""; 
    $.each(data.items, function(i,row){ 
     tblRows += "<tr>";  
     $.each(row, function(j,item){ 
      tblRows +="<td>"+item+"</td>"; 
     }) 
     tblRows += "</tr>"; 
    }) 
    return tblRows; 
} 

我用這樣的:

var e = new JSONRequest(this.id,this.type); 
e.query(); 
alert(e.data); //returns Undefined 

我如何使用返回的JSON對象我在其他類中的方法?

+0

我沒有測試這個,但也許嘗試這樣的事情? var e = new JSONRequest(this.id,this.type); var data = e.query(); alert(data); //返回未定義的 – 2010-08-27 17:06:07

+0

,它仍然返回undefined。我相信這是一個範圍問題。 – 2010-08-27 18:40:12

回答

0

你不能真的從這樣的回調中返回數據。另一個更嚴重的問題就是,getJSON是異步的。所以,你應該做的是傳遞一個回調在query功能,讓您可以有機會獲得這樣的數據:

JSONRequest.prototype.query = function(callback) { 
    $.getJSON(JSONsvc, 
      {request_id:this.request_id, type:this.type}, 
      function(data) { 
       if(callback) { 
        callback(data); 
       }      
      }   
    ); 
}; 

然後:

var e = new JSONRequest(this.id,this.type); 
e.query(function(data) { 
    alert(data); 
}); 

這應該工作。

+0

到目前爲止,這看起來確實具有預期的效果。 – 2010-08-27 18:17:27

相關問題