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

我想用 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>
156651 次浏览

You might want to use encodeURIComponent().

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

You need to url-escape the ampersand. Use:

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

As Wolfram points out, this is nicely handled (along with all the other special characters) by encodeURIComponent.

You can use encodeURIComponent().

It will escape all the characters that cannot occur verbatim in URLs:

var wysiwyg_clean = encodeURIComponent(wysiwyg);

In this example, the ampersand character & will be replaced by the escape sequence %26, which is valid in URLs.

You could encode your string using Base64 encoding on the JavaScript side and then decoding it on the server side with PHP (?).

JavaScript (Docu)

var wysiwyg_clean = window.btoa( wysiwyg );

PHP (Docu):

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

Ramil Amr's answer works only for the & character. If you have some other special characters, you should use PHP's htmlspecialchars() and JS's encodeURIComponent().

You can write:

var wysiwyg_clean = encodeURIComponent(wysiwyg);

And on the server side:

htmlspecialchars($_POST['wysiwyg']);

This will make sure that AJAX will pass the data as expected, and that PHP (in case your'e insreting the data to a database) will make sure the data works as expected.

The preferred way is to use a JavaScript library such as jQuery and set your data option as an object, then let jQuery do the encoding, like this:

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

If you can't use jQuery (which is pretty much the standard these days), use encodeURIComponent.

encodeURIComponent(Your text here);

This will truncate special characters.

You can pass your arguments using this encodeURIComponent function so you don't have to worry about passing any special characters.

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