2013-06-05 130 views
0

我需要將值從PHP傳回給我的javascript。我已經嘗試了很多東西,但無法使其工作。這是我的代碼。需要將值從PHP傳遞到Javascript

<script type="text/javascript">  
    life = {}; 
    life.anjaxEnter = function(finished) { 
     $.ajax({ 
     dataType:"json", 
     type:"POST", 
     data:mydata, 
     url:"myurl.php", 
     async:false, 
     success:life.receiveResult, 
     }); 
     setTimeout("location.href='myredirectionurl'", 1000); // Redirect after 1 second 
    } 
    life.receiveResult = function(result) { 
     alert(result); 
    } 
</script> 

我需要將PHP文件中的特定值傳回給life.receiveResult,然後將其添加到重定向url。

+0

可能重複[如何將這些字符串從PHP傳遞到JavaScript](http://stackoverflow.com/questions/3174092/how-to-pass-these-strings-from-php-to-javascript)和http ://stackoverflow.com/questions/8626183/passing-values-from-php-to-javascript?rq = 1 –

+2

你有一個額外的逗號後susccess – stackErr

+0

你可以搜索之前發佈的問題。我看到這個問題在Stack Overflow上回答了幾十次。 –

回答

2

最大的問題可能是,當時當你將life.receiveResultsuccesslife.receiveResultundefined。在將其分配給其他內容之前,您需要對其進行定義。

0

myurl.php調用時需要返回JSON結果。事情是這樣的:

<?php 
header("Content-Type: text/json"); 
$mydata = "Hello"; 
echo json_encode(array('ok' => true, 'mydata' => $mydata)); 
?> 

看一看的json_encode文檔中,header docs和一些otheranswers以獲取更多信息。