【问题标题】:$_GET the value of (&) with AJAX$_GET 使用 AJAX 获取 (&) 的值
【发布时间】:2013-05-09 02:43:24
【问题描述】:

我有三个代码第一个是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) 代码 &amp; 并单击按钮时;它必须打印出hello&amp;
但它打印hello!!
只有hello 没有&amp;

我注意到我正在发送到 php 文件是这样的: file.php?a=hello&amp;b=&amp;.
最后一个&amp; 必须是%26

所以要打印出&amp;,我必须发送: file.php?a=hello&amp;b=%26.

我该如何解决这个问题??

【问题讨论】:

  • 你不能,真的。 &amp; 在查询字符串中具有特殊含义——它是参数分隔符。如果要将其作为值包含,则需要对其进行编码。

标签: php html ajax


【解决方案1】:

JavaScript 中的更改:

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

【讨论】:

    【解决方案2】:

    您必须对您的值进行 URL 编码:

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

    你需要这个,因为你的 URL 中的参数被分割成 '&' 等等:

    a=你好 & b= & *(这里可以是第三个参数)*

    【讨论】:

      【解决方案3】:

      我认为,使用 jQuery.AJAX() 会为您解决问题。

      【讨论】:

        【解决方案4】:

        使用 encodeURIComponent()

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

        【讨论】:

          【解决方案5】:

          要在 URL 中编码与号 (&),请使用 &amp;amp;。当你用它替换它时会发生什么?

          【讨论】:

          • 问题不在于 & 在 HTML 中。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-24
          • 2020-05-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多