带有'&'的参数打破了AJAX Call

Jba*_*ann 1 javascript ajax

虽然这几乎是这个问题的重复: 参数带有'&'打破$ .ajax请求,给出的答案不是帮助我解决问题的答案.原因是,问题和答案都是jQuery(我不明白).

我需要发送一个带有字符串参数的Ajax调用,该参数有时包含"RGR Kabel GmbH&Co.KG"中的"&".

例如,我有这个AJAX函数(简化):

function getData()
{
    var param = "RGR Kabel GmbH & Co. KG";
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
        {
        [... do something]
        }
    };
    xmlhttp.open("GET", "../getData.php?q1="+param, true);
    xmlhttp.send();
}
Run Code Online (Sandbox Code Playgroud)

param变量中的'&' 打破了AJAX调用.而不是一个参数:

q1 : "RGR Kabel GmbH & Co. KG"
Run Code Online (Sandbox Code Playgroud)

有两个参数:

q1 : "RGR Kabel GmbH "
Co. KG : 
Run Code Online (Sandbox Code Playgroud)

在参数中使用'&'时,是否有可能阻止AJAX调用中断?

任何帮助是极大的赞赏!

Chr*_*son 8

由于&在URI中分离查询字符串参数的目的是,如果要发送包含该字符的数据,则必须在将所有数据添加到URI之前对其进行编码.你可以用它encodeURIComponent()来实现这个目的.

在你的情况下像这样:

xmlhttp.open("GET", "../getData.php?q1="+encodeURIComponent(param), true);
Run Code Online (Sandbox Code Playgroud)

  • @Jbartmann这取决于您使用的服务器语言。对于PHP,对于.Net来说应该是[`urldecode()`](http://se1.php.net/manual/zh/function.urldecode.php),您可以使用[`HttpUtility.UrlDecode()`](http ://msdn.microsoft.com/en-us/library/adwtk1fy.aspx)。其他语言将具有类似的方法。“ URL解码”是您想要的词。 (2认同)