我正在使用基本的$ .ajax()通过jQuery执行异步HTTP(Ajax)请求.代码如下所示:
$("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!" );
}
});
});
Run Code Online (Sandbox Code Playgroud)
一切都像往常一样正常工作,直到用户键入textarea&符号(&)字符.比我调试PHP函数时,它保存了值,它总是有一个值,直到这个字符.
我相信必须有一个解决方案以某种方式跳过&符号.有任何想法吗?
Dar*_*rov 84
代替:
data: "id=" + thisId + "&value=" + thisValue
Run Code Online (Sandbox Code Playgroud)
做:
data: { id: thisId, value: thisValue }
Run Code Online (Sandbox Code Playgroud)
这样jquery将负责对值进行正确的URL编码.字符串连接是所有邪恶的根源:-)
T.J*_*der 27
强烈建议您尽可能使用上述Darin提供的解决方案 ; 这样,您就可以重用经过良好测试的代码来构建POST
数据.
但是,如果您确实真的需要使用字符串连接(在此处或应用程序中的其他位置,在构建查询字符串或POST
用户输入数据时),您需要使用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!" );
}
});
});
Run Code Online (Sandbox Code Playgroud)
默认情况下,在发送POST
with时jQuery.ajax
,您将使用内容类型发送数据application/x-www-form-urlencoded
,这意味着您承诺数据以这种方式进行编码.你必须确保保持你的讨价还价的一部分,并实际编码.这对于&符号来说不仅重要.
只需使用javascript函数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!" );
}
});
});
Run Code Online (Sandbox Code Playgroud)