2013-05-14 55 views
2

值我有三個碼,第一個是html

<html> 
<head> 
<script type = "text/javascript" src = "AJAX.js"></script> 
</head> 

<body> 
<form method = "GET" > 
    <input type = "text" id ="a" ><br> 
    <input type = "text" id = "b"><br> 
    <input type = "button" value ="click" onclick = "process()"><br> 
    <textarea id = "underbutton" ></textarea><br> 
</form> 
<body> 
</html> 

現在使用Javascript(AJAX):

function process() { 
    if(xmlHttp.readyState==0 || xmlHttp.readyState==4){ 

     a = document.getElementById("a").value; 
       b = document.getElementById("b").value; 
     xmlHttp.onreadystatechange = handleServerResponse; 
     xmlHttp.open("GET","file.php?a="+a+"&b="+b,true); 
     xmlHttp.send(); 
    } 
} 

function handleServerResponse(){ 
    if(xmlHttp.readyState==4 && xmlHttp.status==200) 
     { 

     response = xmlHttp.responseText; 
     document.getElementById("underbutton").innerHTML = response ; 


     } 

} 

現在PHP文件:

<?php 

echo $_GET['a'].'<br>'; 
echo $_GET['b'].'<br>'; 

?> 

一切正常,但問題是當我鍵入第一個texbox(a)字hello和第二(b)th e代碼&並點擊按鈕;它必須打印出hello&
但它打印hello
只是hello沒有&

我注意到,我會發送到PHP文件是這樣的: file.php?a=hello&b=&
最後&必須%26

所以打印出來&我必須發送: file.php?a=hello&b=%26

我該如何解決?

+0

你不能,真的。 '&'在查詢字符串中有特殊含義 - 它是參數分隔符。如果你想把它作爲一個值包含它,它需要被編碼。 – andrewsi 2013-05-14 17:51:21

+0

http://stackoverflow.com/questions/11294107/how-can-i-send-the-ampersand-character-via-ajax – ioums 2013-05-14 17:54:03

回答

3

變化在JavaScript:

- a = document.getElementById("a").value; 
- b = document.getElementById("b").value; 
+ a = encodeURIComponent(document.getElementById("a").value); 
+ b = encodeURIComponent(document.getElementById("b").value); 
1

使用jQuery.AJAX()會照顧這個問題的你,我想。

3

你必須URL編碼您的值:

xmlHttp.open("GET","file.php?a="+encodeURIComponent(a)+"&b="+encodeURIComponent(b),true); 

你需要這個,因爲在你的URL參數是分裂的 '&' 等它像:

A =你好 & b = & *(這裏可能是第三個參數)*

0

來編碼的網址符號(&),您可以使用&amp;。當你用它替換它會發生什麼?

+0

這個問題不在HTML中。 – Sven 2013-05-15 19:57:54

1

使用encodeURIComponent方法()

xmlHttp.open("GET","file.php?a="+encodeURIComponent(a)+"&b="+encodeURIComponent(b),true);