2009-08-07 50 views
0

我正在使用帶Prototype庫的Ajax。在原型中的onSuccess函數內部設置訪問值

這是我調用Ajax函數的函數。

function Testfn() 
{ 

    var DateExists = ''; 

    new Ajax.Request('testurl',{ 
      method: 'post', 
      parameters: {param1:"A", param2:"B", param3:"C"}, 
      onSuccess: function(response){ 
      //DateExists = response.responseText; 
          DateExists = 1; 
     } 
     }); 
    // I want to access the value set in the onsuccess function here 
    alert(DateExists); 

} 

當我提醒DateExists值我得到的而不是在我的Ajax調用是1的功能的onSuccess設置的值空值這怎麼可能?

感謝您的任何幫助。

回答

1

的回調的onSuccess是異步執行的,所述 JAX請求結束時,使所述警報被燒成之前回調被調用。

您應該與響應工作,回調裏面,或者如果你想,讓另一個功能:

new Ajax.Request('testurl',{ 
      method: 'post', 
      parameters: {param1:"A", param2:"B", param3:"C"}, 
      onSuccess: function(response){ 
         var dateExists = response.responseText; 
         doWork(dateExists); 
         // or alert(dateExists); 
       } 
     }); 

function doWork (data) { 
    alert(data); 
} 
3

Ajax中的A代表異步。這意味着只要您使用new Ajax.Request發送該Ajax請求,該請求就會發送到服務器,並立即將控制權返回給您的腳本。因此,警報(DateExists)會顯示您最初設置的「'。

要從AJAX請求返回後查看DateExists的值,必須將其移入onSuccess()方法內。

實施例:

function Testfn() { 

    var DateExists = ''; 

    new Ajax.Request('testurl', { 
     method: 'post', 
     parameters: {param1:"A", param2:"B", param3:"C"}, 
     onSuccess: function(response){ 
     DateExists = response.responseText; 
     alert(DateExists); 
     } 
    }); 
} 
0

CMS是完全正確的。解決的辦法是打電話需要從AJAX回調中獲得DateExists的JavaScript,像這樣:

function Testfn() 
{ 

    var DateExists = ''; 

    new Ajax.Request('testurl',{ 
    method: 'post', 
    parameters: {param1:"A", param2:"B", param3:"C"}, 
    onSuccess: function(response){ 
     //DateExists = response.responseText; 
     DateExists = 1; 
     doTheRestOfMyStuff(DateExists); 
    } 
    }); 
    // I want to access the value set in the onsuccess function here 
    function doTheRestOfMyStuff(DateExists) 
    { 
    alert(DateExists); 
    } 
} 
+0

誠實的問題:如果我迅速做出反應的一個問題,但留下我的答案不完整,然後再花幾分鐘的時間回去編輯我的答案,它是否顯示爲在原始發佈日期已被回答?因爲在這個問題中,我在上面的兩個答案之前發佈了這個js示例,但現在看起來好像我複製了它們。 – stereoscott 2009-08-07 06:03:18

+0

它顯示您原始回覆的時間。 – hobodave 2009-08-07 06:13:11