The task is to send a POST request through Ajax to the server. But the problem occurs if you transmit a string with an ampersand. She is cut off from him. I can not cope.

Script:

function XmlHttp() { var xmlhttp; try{xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");} catch(e) { try {xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");} catch (E) {xmlhttp = false;} } if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp = new XMLHttpRequest(); } return xmlhttp; } function ajax(param) { if (window.XMLHttpRequest) req = new XmlHttp(); method=(!param.method ? "POST" : param.method.toUpperCase()); if(method=="GET") { send=null; param.url=param.url+"&ajax=true"; } else { send=""; for (var i in param.data) send+= i+"="+param.data[i]+"&"; send=send+"ajax=true"; } req.open(method, param.url, true); if(param.statbox)document.getElementById(param.statbox).innerHTML = '<img src="/images/wait.gif" width="100">'; req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); req.send(send); req.onreadystatechange = function() { if (req.readyState == 4 && req.status == 200) //если ответ положительный { if(param.success)param.success(req.responseText); } } } 

The form:

 <input type="text" maxlength="100" id="url" name="url" /> <a href="javascript:return false;" onclick="off(); ajax({url:'/serv.php',statbox:'status2',method:'POST',data:{container:document.getElementById('url').value,},success:function(data){document.getElementById('status2').innerHTML=data;}}); return false;"><span>Отправить</span></a> 

Could there be potential problems with other characters? A link is passed through the form.

  • "She is clipped from him." - ??? Do you want to explain what is cut off from what? - Igor
  • For example, if you send a link to the server primer.com/?ddd=1&aaa=2 , then come primer.com/?ddd=1 - Vadim
  • The crutch will also work - Vadim
  • And you can not use the finished library? - Mikhail Vaysman
  • No, I save-paste the skin - Vadim

1 answer 1

For this there is a special function encodeURI . Escapes not only the ampersand, but also other "illegal" characters.

In your case, you need to escape the send variable:

 req.send(encodeURI(send)); 

Ps. It would be better to rename the send variable, by the way. See, for example, https://msdn.microsoft.com/ru-ru/library/ms229012(v=vs.110).aspx : ✓ DO name fields using a noun, noun phrase, or adjective. The same rule applies to variables: send is a verb, better use a noun.

  • Understood it, but I can not understand what to wrap in this function. Experiments did not lead to anything. Everything connected with the client causes me a stupor. - Vadim