2011-11-18 102 views
3

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

我想作为参数传递给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服务器上。

回答

7

为什么不这样做以下:

$.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); 
5

您可以使用.param;

dataString = $.param({first: asChar, second: doesntHave}); 
8

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

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) { 
    } 
}); 
1

,或者如果你想跳过$.param部分由@亚历克斯-K文件档案化

data : {'first': hasChar, 'second': doesntHave}, 
0

如果您希望服务器端的de /编码使用urlencode()urldecode()

+0

这是不是一个真正的问题的答案。 – kapa

+0

@bazmegakapa:这是 - 编辑了这个问题。 “如何在_server_一侧对字符串进行编码......”是原始问题。 –

+0

这是一个错字... – kapa

1

只需将它作为一个对象:

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) { 
    } 
}); 
0

试试这个

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) { 
    } 
}); 
1

您还可以使用encodeURI

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

Link

0

你的参数需要简单的URL编码。在PHP方面,你不需要解码它们,一切都会正常工作。

有一个Javascript函数,名为encodeURIComponent(),它将正确地对您的字符串进行网址编码。因此,在基础层面上,你可以这样做:

var dataString = "first=" + encodeURIComponent(hasChar) + "&second=" + encodeURIComponent(doesntHave); 

如果你使用jQuery,它会自动处理这对你来说,如果in your $.ajax() call you pass it an object instead of a query string

数据选项可以包含的查询字符串形式 key1 = value1 & key2 = value2,或形式为{key1:'value1',key2: 'value2'}的地图。如果使用后一种形式,则在发送数据之前使用jQuery.param()将数据转换为 查询字符串。

所以你只需要做到这一点在你的代码:

var dataString = { first: hasChar, second: doesntHave);