2013-07-08 28 views
0

嘗試將變量傳遞給PHP文件,然後獲取該文件的輸出。JavaScript to pass變量並從PHP頁面檢索輸出

Page1.html:

<h2 id="test"></h2> 
<script> 
var data2; 
$.post('textandemail.php',{ txt: "John", email: "[email protected]" }, 
    function(data) { 
data2 = data;}); 
document.getElementById("test").innerHTML = data2; 
</script> 

textandemail.php:

$variable = $_POST["txt"]; 
    $variable2 = $_POST["email"]; 
    echo $variable; 
    echo $variable2;  

希望這說明了所需的想法。我將在PHP文件中做更多的事情,但最終會迴應我希望JavaScript讀取並實現到HTML頁面的響應。

回答

1

$.post()函數是異步的。它稍後完成。您需要將該函數的結果分配到成功處理程序中,而不是在函數本身之後,因爲現在您已經有該行,因此document.getElementById("test").innerHTML = data2;行正在發生之前ajax函數完成,因此它不起作用。

這是你如何能做到這一點:

<h2 id="test"></h2> 
<script> 
$.post('textandemail.php',{ txt: "John", email: "[email protected]" }, 
    function(data) { 
     // any code that uses the ajax results in data must be here 
     // in this function or called from within this function 
     document.getElementById("test").innerHTML = data; 
    } 
); 
</script> 

或者,因爲你有jQuery的,你可以做這樣的:

<h2 id="test"></h2> 
<script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
<script> 
$.post('textandemail.php',{ txt: "John", email: "[email protected]" }, 
    function(data) { 
     // any code that uses the ajax results in data must be here 
     // in this function or called from within this function 
     $("#test").html(data); 
    } 
); 
</script> 
+0

感謝您的回覆的功能! java腳本不工作...我沒有得到任何東西放在h2標籤之間...嘗試jQuery現在 –

+0

既不工作任何想法? –

+0

啊我傻了我註釋了一個大塊,包括jquery的腳本src ... ahhhh .... woshhhhh回去工作.....謝謝! –

1

您的文章調用是異步的,你只能訪問一次,這個過程完成了data2變量,所以你應該做的回調函數你....innerHTML ...,當數據是可用的,而不是之前。

在任何js網站上都有很多很好的例子。在jQuery doc你有一個很好的例子。 由於您使用的是jQuery,因此您也可以替換您的innerHTML調用。

1

你應該使用AJAX功能使PHP之間的通信和javascript

function Ajax_Send(GP,URL,PARAMETERS,RESPONSEFUNCTION){ 
var xmlhttp 
try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")} 
catch(e){ 
try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")} 
catch(e){ 
try{xmlhttp=new XMLHttpRequest()} 
catch(e){ 
alert("Your Browser Does Not Support AJAX")}}} 

err="" 
if (GP==undefined) err="GP " 
if (URL==undefined) err +="URL " 
if (PARAMETERS==undefined) err+="PARAMETERS" 
if (err!=""){alert("Missing Identifier(s)\n\n"+err);return false;} 

xmlhttp.onreadystatechange=function(){ 
if (xmlhttp.readyState == 4){ 
if (RESPONSEFUNCTION=="") return false; 
eval(RESPONSEFUNCTION(xmlhttp.responseText)) 
} 
} 

if (GP=="GET"){ 
URL+="?"+PARAMETERS 
xmlhttp.open("GET",URL,true) 
xmlhttp.send(null) 
} 

if (GP="POST"){ 
PARAMETERS=encodeURI(PARAMETERS) 
xmlhttp.open("POST",URL,true) 
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded") 
xmlhttp.setRequestHeader("Content-length",PARAMETERS.length) 
xmlhttp.setRequestHeader("Connection", "close") 
xmlhttp.send(PARAMETERS)  

調用函數把它放在javascript頁面裏

Ajax_Send("POST","users.php",data,e) 

其中數據發送到PHP頁面和E的數據是你的PHP頁面的輸出傳遞給它

+0

謝謝!回覆 –

+0

爲什麼所有這些,如果他們已經有jQuery。 – jfriend00