2012-01-03 32 views
2

我有一個對象的構造函數:使用jQuery AJAX調用來填充動態對象

function Context(tid) { 
    this.tid = tid; 
    var self = this; 

//We get all the data we need from the server to use in this Context. 
$.post(
    '/review/context/get_context', 
    {tid: tid}, 
    function(data) { 
    results = $.parseJSON(data); 
    if(results.status == "SUCCESS") { 
     self.obj = results.object; 
     self.currenttodo = results.tid 
    } 
    } 
); 

}

我想發起一個文檔加載,並使用該對象,直到和事件觸發要改變的對象,在這一點上,我想擦除該對象,並用來自不同Ajax調用的信息重新啓動它。在這裏使用一個對象是可取的,因爲有一大堆適用於所有上下文的函數。

$(document).ready(function() { 
    cc = new Context($('#context-tabs').attr('name')); 
    console.log(cc); 
    console.log(cc.currenttodo); 
} 

生成以下控制檯輸出:

Context 
currenttodo: 14 
obj: Object 
tid: "1" 
__proto__: Context 

undefined 

我覺得這是這個是不是後續功能的執行之前完成asynchonous函數的標準情況下,但我有幾個問題:

1)爲什麼我可以直接在console.log之前直接在console.log中查看cc.currenttodo的值,但無法訪問它? 2)爲什麼Chrome console.log輸出對於兩個整數不同。 14不是引號和藍色,而tid:「1」是紅色的並用引號引起來。我認爲這表明tid是一個字符串,但我想確認一下。 3)如果我不能以這種方式使用異步調用,我將實例化一個唯一對象,以用於從服務器調用填充的調用$ document.ready()函數中?我認爲我需要通過成功:函數來完成它,但似乎無法獲得除self.variables之外的任何內容嗎?

在此先感謝。

UPDATE:SO不會讓我回答我自己的問題呢,所以這裏是工作代碼:

function Context(tid) { 
    this.tid = tid; 
    var self = this; 

    //We get all the data we need from the server to use in this Context. 
    $.ajax({ 
    url: "/review/context/get_context", 
    type: "POST", 
    data: "tid="+self.tid, 
    async: false, 
    dataType: "json", 
    success: function(data) { 
     if(data.status == "SUCCESS") { 
     self.obj = data.object; 
     self.currenttodo = data.tid; 
     } 
    } 
    }); 
} 
+0

內調出一個實例化對象在似乎不可能得到的結果這種情況下,異步通過成功函數回調到實例化對象的範圍,但設置async:false有效。我確實需要將jQuery的$ .post調用轉換爲$ .ajax,但這沒什麼大不了的: – samtresler 2012-01-03 18:43:40

回答

1

1)假設你要在控制檯中點擊檢查對象,這是因爲當你點擊的時候,通話已經完成,並且Chrome已經足夠了解你正在嘗試查看的內容。 console.logs雖然立即發生,所以立即請求cc.currentodo意味着它當時不知道。

2)正確:「1」是一個字符串。檢查JSON響應並查看它發送的內容以確認。

3)您可以使用成功功能,也可以同步運行POST。我會說繼續在前者工作。一般來說,處理異步時序是棘手的,但一旦你有它的工作,它是非常強大的。

0

用於實例化上述對象的代碼示例。正如指出的那樣,異步:假是關鍵,否則你不能泡一個AJAX的結果constucter

function Context(tid) { 
    this.tid = tid; 
    var self = this; 

    //We get all the data we need from the server to use in this Context. 
    $.ajax({ 
    url: "/review/context/get_context", 
    type: "POST", 
    data: "tid="+self.tid, 
    async: false, 
    dataType: "json", 
    success: function(data) { 
     if(data.status == "SUCCESS") { 
     self.obj = data.object; 
     self.currenttodo = data.tid; 
     } 
    } 
    }); 
}