I am performing asynchr开发者_如何学JAVAonous HTTP (Ajax) requests via jQuery with the basic $.ajax(). The code looks like the following:
$("textarea").blur(function(){
var thisId = $(this).attr("id");
var thisValue = $(this).val();
$.ajax({
type: "POST",
url: "some.php",
data: "id=" + thisId + "&value=" + thisValue,
success: function(){
alert( "Saved successfully!" );
}
});
});
Everything is working properly as usual, until user types inside textarea ampersand (&) character. Than when I debug PHP function, which saves the value, it always have a value until this character.
I believe there has to be a solution to skip ampersand (&) somehow. Any ideas?
Instead of:
data: "id=" + thisId + "&value=" + thisValue
do:
data: { id: thisId, value: thisValue }
This way jquery will take care of properly URL encoding the values. String concatenations are the root of all evil :-)
Strongly recommend you use the solution provided by Darin above if at all possible; that way, you get to reuse well-tested code for building POST
data.
But if you really, really, really need to use string concatenation (here, or elsewhere in your application when building up query strings or POST
data out of user inputs), you need to use encodeURIComponent
:
$("textarea").blur(function(){
var thisId = $(this).attr("id");
var thisValue = $(this).val();
$.ajax({
type: "POST",
url: "some.php",
data: "id=" + encodeURIComponent(thisId) + "&value=" + encodeURIComponent(thisValue),
success: function(){
alert( "Saved successfully!" );
}
});
});
By default when sending a POST
with jQuery.ajax
, you're sending data with the content type application/x-www-form-urlencoded
, which means you're promising that the data is encoded that way. You have to be sure to keep your part of the bargain and actually encode it. This isn't just important for ampersands.
just use the javascript function encodeURIComponent()
:
$("textarea").blur(function(){
var thisId = $(this).attr("id");
var thisValue = $(this).val();
$.ajax({
type: "POST",
url: "some.php",
data: "id=" + thisId + "&value=" + encodeURIComponent(thisValue),
success: function(){
alert( "Saved successfully!" );
}
});
});
$.ajax({
type:'POST',
dataType: "text",
url:'save.php',
data:'_id='+$('#id').val()+'&title='+$('#title').val(),
??
data: { id: thisId, value: thisValue }
精彩评论