2010-08-27 64 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

相关问题