问题描述:

I am using Ajax POST method to send data, but i am not able to send '+'(operator to the server i.e if i want to send 1+ or 20k+ it will only send 1 or 20k..just wipe out '+')

HTML code goes here..

<form method='post' onsubmit='return false;' action='#'>

<input type='input' name='salary' id='salary' />

<input type='submit' onclick='submitVal();' />

</form>

and javascript code goes here,

function submitVal()

{

var sal=document.getElementById("salary").value;

alert(sal);

var request=getHttpRequest();

request.open('post','updateSal.php',false);

request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

request.send("sal="+sal);

if(request.readyState == 4)

{

alert("update");

}

}

function getHttpRequest()

{

var request=false;

if(window.XMLHttpRequest)

{

request=new XMLHttpRequest();

}

else if(window.ActiveXObject)

{

try

{

request=new ActiveXObject("Msxml2.XMLHTTP");

}

catch(e)

{

try

{

request=new ActiveXObject("Microsoft.XMLHTTP");

}

catch(e)

{

request=false;

}

}

}

return request;

}

in the function submitVal() it first alert's the salary value as it is(if 1+ then alerts 1+), but when it is posted it just post's value without '+' operator which is needed...

is it any problem with query string, as the PHP backend code is working fine...

网友答案:

Use

request.send("sal="+encodeURIComponent(sal));

The + is interpreted as an space on the server side so you need to encode the string first.

More info here:

http://xkr.us/articles/javascript/encode-compare/

网友答案:

You need to encode sal in request.send("sal="+sal). You'll probably find that if sal was equal to "foo & bar", you would end up with just "foo" on the server since the & needs to be encoded too. So:

request.send("sal=" + encodeURIComponent(sal)); // updated example

However, rather than doing this all by hand, you should think about using a library to do it for you, such as jQuery, then your example would look something like this:

$.ajax({
   url: "updateSal.php",
   type: "POST",
   data: { sal : $("salary").val() },
   success: function(){
      alert("update");
   }
});
相关阅读:
Top