2015-01-13 33 views
-1

收到「後」 variabe我送這是我的javascript:我的PHP無法通過AJAX

function fetchprov(proptype) { 
    var reqdata = "condo="+proptype; 
    hanapin=new XMLHttpRequest(); 
    hanapin.open('POST', 'testajax.php', true); 
    hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded") 
    hanapin.send(reqdata); 
    hanapin.onreadystatechange = function() { 
     if (hanapin.readyState == 4 && hanapin.Status == 200) { 
      document.getElementById('province').innerHTML=hanapin.ResponseText 
     } 
    } 
    window.alert(targeturl); 
    window.alert(reqdata); 
} 

我所知道的功能是接收數據,因爲我使用的警報。

但在PHP:

<?php 
    $findwat = $_POST['condo']; 
    echo $findwat; 
?> 

甚至當我使用一個單獨的鏈接打開PHP文件也不會回聲可變

+2

使'$ _POST' – Shubanker

+1

一個的var_dump「當我使用單獨的鏈接打開php文件,它不會回顯變量「你如何用http post打開頁面? – atmd

+0

像這樣var_dump($ _ POST);? –

回答

0

一個例子:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 

function fetchprov(proptype) { 
    $.post("testajax.php", {condo:proptype}, function(data){ 
     // data is the result received from php 
     alert(data); 
    }); 
} 
+0

是的。這一個工作完美....謝謝。 –

0

一個強制報頭的HTTP POST請求字段是Content-length。更改您的代碼:

function fetchprov(proptype) { 
    var reqdata = "condo="+proptype; 
    hanapin=new XMLHttpRequest(); 
    hanapin.open('POST', 'testajax.php', true); 
    hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    hanapin.setRequestHeader("Content-length", reqdata.length); 
    hanapin.setRequestHeader("Connection", "close"); 
    hanapin.send(reqdata); 
    hanapin.onreadystatechange=function() {if (hanapin.readyState == 4 && hanapin.Status == 200) {document.getElementById('province').innerHTML=hanapin.ResponseText} } 
    window.alert(targeturl); 
    window.alert(reqdata); 
} 

也是一個更好的解決方案是使用jquery使用jQuery處理Ajax