javascript - 带有 '&' 的参数打破了 $.ajax 请求

标签 javascript jquery parameter-passing

我正在开发一个 Web 应用程序,它在客户端使用 JavaScript + JQuery,在服务器端使用 PHP。

我想作为 AJAX 请求的参数传递的字符串之一在其内容中包含“&”。

由于这个原因,请求的字符串被破坏了。浏览器“认为”这个参数结束了,因为字符串上有一个'&'。

var hasChar = "This is a string that has a & in the content.";
var doesntHave = "This one does not contain.";
var dataString = "first=" + hasChar + "&second=" + doesntHave;

$.ajax({
    type : "POST",
    url : "myurl.php",
    data : dataString,
    cache : false,
    success : function(html) {
    }
});

服务器接收到的第一个参数是“This is a string that has a”

我的问题:

我如何在客户端对字符串进行编码以及我应该如何在 PHP 服务器上对其进行解码。

最佳答案

让 jQuery 为您处理 hasChar(和您的其他参数)的编码:

var hasChar = "This is a string that has a & in the content.";
var doesntHave = "This one does not contain.";

$.ajax({
    type : "POST",
    url : "myurl.php",
    data : { first: hasChar, second: doesntHave },
    cache : false,
    success : function(html) {
    }
});

关于javascript - 带有 '&' 的参数打破了 $.ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8184438/

相关文章:

javascript - 如何评估函数声明中的变量?

javascript - 为什么点击在触摸模式下不起作用

javascript - 如何使用 toggleClass 为检测到的特定类更改 css 类

javascript - HTML5 重置视频并重新播放

javascript - 如何获取指针字段带有 objectId 的记录?

Javascript,计算有多少文件附加到文件上传输入

java - 如何在 JSF 2 的值表达式和方法表达式中传递参数?

使用特定键将字典作为参数传递的 Pythonic 方式

bash 脚本因多个参数而失败

javascript - 使用react js、babel和es6导入随机文件