如何发送“&”通过AJAX(&符号)角色?

时间:2012-07-02 12:54:21

标签: javascript ajax string post xmlhttprequest

我想从JavaScript发送一些变量和一个带POST方法的字符串。我从数据库中获取字符串,然后将其发送到PHP页面。我正在使用XMLHttpRequest对象。 问题是该字符串包含字符“&”几次,PHP中的$ _POST数组看起来像多个键。 我试过更换“&”与“\&”使用replace()函数,但似乎没有做任何事情。 有人可以帮忙吗?

javascript代码和字符串如下所示:

    var wysiwyg = dijit.byId("wysiwyg").get("value");
var wysiwyg_clean = wysiwyg.replace('&','\&');

var poststr = "act=save";
poststr+="&titlu="+frm.value.titlu;
poststr+="&sectiune="+frm.value.sectiune;
poststr+="&wysiwyg="+wysiwyg_clean;
poststr+="&id_text="+frm.value.id_text;     
xmlhttp.open("POST","lista_ajax.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(poststr);

字符串是:

 <span class="style2">&quot;Busola&quot;</span>

8 个答案:

答案 0 :(得分:150)

您可以使用encodeURIComponent()

它将转义URL中不能逐字出现的所有字符:

var wysiwyg_clean = encodeURIComponent(wysiwyg);

在此示例中,&符号&将替换为在URL中有效的转义序列%26

答案 1 :(得分:15)

您可能想要使用encodeURIComponent()

encodeURIComponent("&quot;Busola&quot;"); // => %26quot%3BBusola%26quot%3B

答案 2 :(得分:8)

你需要url-escape&符号。使用:

var wysiwyg_clean = wysiwyg.replace('&', '%26');

Wolfram指出,通过encodeURIComponent可以很好地处理(以及所有其他特殊字符)。

答案 3 :(得分:4)

Ramil Amr的回答仅适用于&amp;字符。如果您有其他特殊字符,则应使用PHP的htmlspecialchars() JS的encodeURIComponent()

你可以写:

var wysiwyg_clean = encodeURIComponent(wysiwyg);

在服务器端:

htmlspecialchars($_POST['wysiwyg']);

这将确保AJAX按预期传递数据,并且PHP(如果您将数据存入数据库)将确保数据按预期工作。

答案 4 :(得分:1)

首选方法是使用jQuery等JavaScript库并将数据选项设置为对象,然后让jQuery进行编码,如下所示:

$.ajax({
  type: "POST",
  url: "/link.json",
  data: { value: poststr },
  error: function(){ alert('some error occured'); }
});

如果你不能使用jQuery(这几乎是标准),请使用encodeURIComponent

答案 5 :(得分:0)

您可以在JavaScript端使用Base64编码对字符串进行编码,然后使用PHP(?)在服务器端对其进行解码。

JavaScript(Docu

var wysiwyg_clean = window.btoa( wysiwyg );

PHP(Docu):

var wysiwyg = base64_decode( $_POST['wysiwyg'] );

答案 6 :(得分:0)

encodeURIComponent(Your text here);

这将截断特殊字符。

答案 7 :(得分:0)

您可以使用该encodeURIComponent函数传递参数,因此您不必担心传递任何特殊字符。

data: "param1=getAccNos&param2="+encodeURIComponent('Dolce & Gabbana') 

OR

var someValue = 'Dolce & Gabbana';
data: "param1=getAccNos&param2="+encodeURIComponent(someValue)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent