是否有更好的方法来替换字符串,因为文本区域中的 & 会破坏脚本,因为它认为它是另一个 & 参数?
function doRequest(){
var str = $('textarea#tr').val();
$.ajax({
type: "POST",
url: "index.php?sd=t",
data: "txt="+str.replace(/&/g, "and"),
success: function(){
$("div").css('color','red');
$("div").text('Saved');
$("div").fadeTo(800,1);
$("div").animate({backgroundColor:'#000000'}, 200);
$("div").animate({backgroundColor:'#FFFF90'}, 400);
stre = false;
}
});
}
最佳答案
您可以将数据作为对象传递并让 jQuery 序列化它,如下所示:
data: {txt: str},
请注意,这不会放置单词“and”,它会对其进行转义,留下 %26
。
What actually happens under the covers正在调用encodeURIComponent()
,像这样:
data: "txt="+encodeURIComponent(str),
我会使用第一种方法,我只是展示下面发生的事情,以便更好地理解编码的工作原理。
关于jquery - 替换输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3896311/