2017-02-19 76 views
-1

我从表单中获取输入。输入包含简单的算术运算,如2 + 3。据我所知,输入是正确的。这里chunk包含来自表单输入字段的输入的一小部分。正如你可以看到alert(chuck)给出2 + 3(正确的事情),但是发送'2 + 3'给calculate.php作为参数后得到的响应是2 3(2 space 3)。我的calculate.php只是有一些像echo $ _GET ['param']。XMLHttpRequest和PHP

我对这个主题没有太多经验。这里有什么问题?

chunk = theInput.substring(0,3); 
alert(chunk); //output is 2+3 
document.getElementById("txtHint3").innerHTML = chunk;//output is 2+3 
var xmlhttp = new XMLHttpRequest(); 
xmlhttp.onreadystatechange = function(){ 
if (this.readyState == 4 && this.status == 200) { 
    var response = this.responseText; 
    alert(response); // But here output is 2 3 
    document.getElementById("txtHint223").innerHTML = response; // And same here is 2 3    
     } 
}; 
xmlhttp.open("GET", "calculate.php?param="+chunk,true); 
xmlhttp.send(); 
+0

您应该使用jQuery等框架,而不是尝试手动执行此操作。您的代码不太可能适用于所有浏览器。 – miken32

+0

看到您的PHP代码可能也是有用的,因为这是在做这里的大部分工作 – RiggsFolly

回答

1

+代表查询字符串中的空格。使用encodeURIComponent()正确编码该值:

xmlhttp.open("GET", "calculate.php?param="+encodeURIComponent(chunk),true); 
+0

谢谢...它现在可以工作... 你能给我一点解释,为什么它是必要的? – Smizz

+0

因为查询字符串使用百分比编码。有些字符有特殊含义(如'+')。 https://en.wikipedia.org/wiki/Query_string#URL_encoding – ShiraNai7