2012-07-22 37 views
0

我有這樣的情況。有選擇形式就像是如下圖所示,要AJAX調用函數來得到結果取決於平變化選擇的形式,但是從阿賈克斯取得結果整個頁面,儘管預期值

及彼整個頁面的腳本

<html> 
<head> 
    <title>HI</title> 
    <link rel="stylesheet" href="./scripts/css/default.css"> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
</head> 
<body> 

<form method="post"> 
<select name="s" id="s"> 
    <option value="one">A</option> 
    <option value="two">B</option> 
    <option value="three">C</option> 
</select> 
</form> 

Hello guys ... 
<div id="xe"></div> 

<script type="text/javascript"> 
document.getElementById("s").onchange = function(){ 
    var h = false; 
    if (window.XMLHttpRequest){ 
     h = new XMLHttpRequest(); 
    } 
    if (h){ 
     h.open("POST","index.php",true); 
     h.onreadystatechange = function(){ 
      if (h.readyState==4 && h.status==200){ 
       document.getElementById("xe").innerHTML = h.responseText; 
      } 
     }; 
     h.send("s=" + document.getElementById("s").value); 
    } 
}; 
</script> 

<?php 
if (isset($_POST['s'])){ 
    echo $_POST['s']; 
} 
?> 


</body> 
</html> 

什麼想法?請幫忙,謝謝...

回答

1

你需要將你的文件,並退出(頂部$ _ POST線)算賬:

<?php 
if (isset($_POST['s'])){ 
    echo $_POST['s']; 
    exit; 
} 
?> 
<html> 
<head> 
    <title>HI</title> 
    <link rel="stylesheet" href="./scripts/css/default.css"> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
</head> 
<body> 

<form method="post"> 
<select name="s" id="s"> 
    <option value="one">A</option> 
    <option value="two">B</option> 
    <option value="three">C</option> 
</select> 
</form> 

Hello guys ... 
<div id="xe"></div> 

<script type="text/javascript"> 
document.getElementById("s").onchange = function(){ 
    var h = false; 
    if (window.XMLHttpRequest){ 
        h = new XMLHttpRequest(); 
    } 
    if (h){ 
        h.open("POST","index.php",true); 
        h.onreadystatechange = function(){ 
            if (h.readyState==4 && h.status==200){ 
                document.getElementById("xe").innerHTML = h.responseText; 
            } 
        }; 
        h.send("s=" + document.getElementById("s").value); 
    } 
}; 
</script> 


</body> 
</html> 
+0

我已經猜到了,我錯過了http.setRequestHeader(「內容類型」,「應用程序/ x-WWW的形式,進行了urlencoded」);這個說法:) – tnanoba 2012-07-23 09:29:34

+1

太棒了!不要忘記回答你自己的問題,並標記爲完整 – periklis 2012-07-23 09:45:18

1

事實上,index.php返回整個頁面,其所有的HTML嵌入到它。

你可以精心另一個partial.php,返回你需要在你的瀏覽器頁面注入部分,並指出您的AJAX請求給它。

+0

我剛纔寫的例子在這裏,一般我做像你已經回答了(我的意思在其他文件寫入PHP腳本),但結果還是一樣 – tnanoba 2012-07-22 19:20:37

相關問題