2016-06-11 74 views
0

對不起,如果我的標題不清楚,但我不確定如何形成問題/問題。 所以,我有這樣的代碼:

HTML:

<button onclick="test()">test</button><br> 

的javascript:

function test(){ 
    var text="Old text"; 
    $.post('test.php',function(data){ 
     text=data; 
    }); 
    alert(text); 
} 

PHP:

<?php 
    echo "New text"; 
?> 

但在警告框,我得到 「老文」 。 我該如何解決這個問題?

+2

$。員額是AJAX。 AJAX的意思是**異步** JavaScript和XML。你需要閱讀這個:http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call –

回答

3

在郵件回調函數中移動警報。在$ .post正在運行的同時,警報將被執行。

function test(){ 
    var text="Old text"; 
    $.post('test.php',function(data){ 
     text=data; 
     alert(text); 
    }); 

} 

更新:如果你有更多的代碼警報後執行,可以換那些操作的新功能中:

function test(){ 
     var text="Old text"; 
     $.post('test.php',function(data){ 
      text=data; 
      moreActions(text); 
     }); 
    } 

    function moreActions(text){ 
    alert(text); 
    // and more actions to work with TEXT here 
    } 
+0

是的這可以工作,但我想知道是否有一個不同的解決方案,以防我有一些代碼在alert-box之後用文本變量做某些事情。 當然,我也可以移動其他代碼,但我只是想知道。 謝謝! :) – Zvone

+0

好的。我爲此更新了答案。 –

+1

或者返回'$ .post'承諾並在承諾回調中做任何需要的事情 – charlietfl

-2

$ .post()是一個異步函數,因此alert()在您從post()請求獲取數據之前正在執行。嘗試使用jquery.deferred()同步工作

+0

這是非常糟糕的建議。該解決方案不是強制同步執行,而是學習JavaScript。 –

+0

我不認爲OP要同步工作,這隻會讓他誤解JavaScript的這個基本屬性。 – samsonthehero

+0

另外'jQuery.deferred'不以任何方式涉及同步。這只是寫回調的一種更有趣的方式。 –