Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

javascript - How can I send the "&" (ampersand) character via AJAX?

I want to send a few variables and a string with the POST method from JavaScript.

I get the string from the database, and then send it to a PHP page. I am using an XMLHttpRequest object.

The problem is that the string contains the character & a few times, and the $_POST array in PHP sees it like multiple keys.

I tried replacing the & with & with the replace() function, but it doesn't seem to do anything.

Can anyone help?

The javascript code and the string looks like this:

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);

The String is:

 <span class="style2">&quot;Busola&quot;</span>
question from:https://stackoverflow.com/questions/65953143/how-can-special-character-can-send-to-server-side-using-xmlhttprequest-obj

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...