允许在textarea中使用&符号(&)

时间:2014-09-18 11:25:15

标签: javascript jquery html ajax

我用Google搜索但没有运气。

我有一个表单中的textarea,我试图通过jQuery用ajax发送。我的问题是当textarea包含&符号时(&)它会中断。这是在&之后包含&符号(&)的message = "What are the concerns you are looking to address? "+othr+".\n"; var dataString = 'name=' + name + '&email=' + email + '&company=' + company + '&message=' + message + '&othr=' + othr + '&vpb_captcha_code=' + vpb_captcha_code + '&submitted=1'; $.ajax({ type: "POST", url: "contactus-contact-form.php", data: dataString , 之后包含的任何文本。我发送的数据如下:

encodeURIComponent()

我阅读了message = "What are the concerns or security issues you are looking to address? "+othr+".\n"; var data0 = {name: + name + email: + email + company: + company + message: + message + othr: + othr + vpb_captcha_code: + vpb_captcha_code + submitted: "1"}; $.ajax({ type: "POST", url: "contactus-contact-form.php", data: data0, contentType: "application/json; charset=utf-8", dataType: "json", 并试图实现相同但不起作用。有什么指针吗?

编辑:以下内容无法获取文本值:

{{1}}

2 个答案:

答案 0 :(得分:5)

&是用于分隔表单编码数据中的键/值对的字符。如果要将其用作数据的一部分,则需要将其转义。

最简单的方法是让jQuery负责为您构建表单编码字符串。将对象传递给data参数:

$.ajax({  
    type: "POST",  
    data: {
        name: name, 
        email: email, 
        company: company, 
        message: message, 
        othr: othr,
        vpb_captcha_code: vpb_captcha_code,
        submitted: 1
    },
    // etc

如果你真的想手动完成,那么encodeURIComponent功能将起作用:

var dataString = "name=" + encodeURIComponent(name) + "&email=" + encodeURIComponent(email) // etc etc etc

答案 1 :(得分:-2)

你可以使用encodeURIComponent()函数来解决你的问题。你刚刚更改了下面的代码。我认为你已经将textarea值设置为变量othr。你只能使用encodeURIComponent(othr)编码这个变量。这意味着您可以使用encodeURIComponent方法解析textarea值。

 message = "What are the concerns you are looking to address? "+othr+".\n";
var dataString = 'name=' + name + '&email=' + email + '&company=' + company + '&message=' + message + '&othr=' + encodeURIComponent(othr) + '&vpb_captcha_code=' + vpb_captcha_code + '&submitted=1';
$.ajax({  

type: "POST",  

url: "contactus-contact-form.php",  

data: dataString ,
});


message = "What are the concerns or security issues you are looking to address? "+othr+".\n";
var data0 = {name: + name + email: + email + company: + company + message: + message + 
othr: +encodeURIComponent(othr) + vpb_captcha_code: + vpb_captcha_code + submitted: "1"};

$.ajax({  

type: "POST",  
url: "contactus-contact-form.php",  
data: data0,   
dataType: "json",