参数’&’打破$ .ajax请求
我正在开发一个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) { } });
服务器接收第一个参数“这是一个具有”的字符串
我的问题:
如何在客户端编码字符串,以及如何在PHP服务器上解码它。
为什么不这样做:
$.ajax({ type : "POST", url : "myurl.php", data : { 'first': hasChar, 'second': doesntHave }, cache : false, success : function(html) { } });
在这种情况下,jQuery将确保字符串被正确编码。
作为替代方案,您可以使用encodeURIComponent()JS的内置函数来正确编码字符串:
var dataString = "first=" + encodeURIComponent(hasChar) + "&second=" + encodeURIComponent(doesntHave);
让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) { } });
你可以使用.param
;
dataString = $.param({first: asChar, second: doesntHave});
或者如果你想跳过@ alex-k $.param
的$.param
部分
data : {'first': hasChar, 'second': doesntHave},
您可以将其设置为对象:
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) { } });
你也可以使用encodeURI
:
var encodedData = encodeURI(dataString); $.ajax({ type : "POST", url : "myurl.php", data : encodedData, cache : false, success : function(html) { } });
链接
如果你想要服务器端de /编码使用urlencode()
和urldecode()
。
试试这个
var dataString = {}; dataString["hasChar"] = "This is a string that has a & in the content."; dataString["doesntHave"] = "This one does not contain."; $.ajax({ type : "POST", url : "myurl.php", data : dataString, cache : false, success : function(html) { } });
您的参数需要简单地进行URL编码。 在PHP方面,您不需要解码它们,一切都将正常工作。
有一个名为encodeURIComponent()
的Javascript函数可以对您的字符串进行正确的URL编码。 所以在基础层面上,你可以这样做:
var dataString = "first=" + encodeURIComponent(hasChar) + "&second=" + encodeURIComponent(doesntHave);
如果您使用jQuery,它将自动为您处理此问题,如果在$ .ajax()调用中您传递了一个对象而不是查询字符串 :
data选项可以包含forms为key1 = value1&key2 = value2的查询字符串,或者包含{key1:’value1’,key2:’value2′}forms的映射。 如果使用后一种forms,则在发送之前使用jQuery.param()将数据转换为查询字符串。
所以你只需要在代码中执行此操作:
var dataString = { first: hasChar, second: doesntHave);