2011-01-20 71 views
0

完全新的OOP在javascript中,但林嘗試和閱讀所有我可以。從JavaScript中的方法傳遞數據

我創建了一個簡單的測試JavaScript類叫Invoices。發票只有兩種方法。一種方法觸發另一種方法。這部分似乎工作正常。

我的問題在於從一種方法獲取數據對象到另一個。我在第一種方法中發出警報(從我的理解中),此警報應顯示從第二種方法返回的數據...但不是。

任何幫助將不勝感激。噢..我也在使用jquery。

這是我的codez。

function Invoices() 
{ 
    this.siteURL = "http://example.com/"; 
    this.controllerURL = "http://example.com/invoices/"; 
    this.invoiceID = $('input[name="invoiceId"]').val(); 
} 

invoice = new Invoices; 

Invoices.prototype.initAdd = function() 
{ 
    //load customers json obj 
    this.customersJSON = invoice.loadCustomers(); 
    alert(this.customersJSON); 

    //create dropdown 
} 

Invoices.prototype.loadCustomers = function() 
{ 
    $.post(this.controllerURL + "load_customers"), 
    function(data) 
    { 
    return data; 
    } 
} 

回答

2

有兩個問題。首先,$.post是異步的;您必須採用回調方案或使用$.ajax使其同步。其次,你可能是這樣做的:

$.post(this.controllerURL + "load_customers", function(data) { 
    return data; 
}); 

請注意封閉是如何在函數調用的括號中。

+1

感謝您的答覆。我修復了這個語法錯誤。後部分實際上正在工作。我可以看到XHR請求和json響應,但是,警報仍然說未定義。 – Peter 2011-01-20 04:56:01

0

當你被告知AJAX調用是異步的,你會實現你initAdd在2步:

  1. BeginInitAdd這將引發AJAX調用
  2. EndInitAdd這將是回調的AJAX根據返回的數據調用並執行操作。

Invoices.prototype.initAdd = function() 
{ 
    //load customers json obj 
    this.xhrObj = invoice.loadCustomers(); 
    alert(this.customersJSON); 
} 
Invoices.prototype.createDropdown = function (data) { 
    //create dropdown 
    this.customersJSON=data 
} 
Invoices.prototype.loadCustomers = function() 
{ 
    return $.post(this.controllerURL + "load_customers"), 
    function(data) 
    { 
     //return data; 
     this.createDropdown(data) 
    } 
}