允许在文本区域中使用“与”符号(&)

Allowing ampersand (&) in textarea

本文关键字:符号 amp 文本 区域      更新时间:2023-09-26

我在谷歌上搜索了一下,但没有运气。

我有一个表单中的文本区域,我正试图通过ajax和jQuery发送它。我的问题是,当文本区域包含"与"符号(&)时,它会中断。也就是说,&之后包含的任何文本都不会被提取,包括与号(&)。我发送的数据如下:

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",

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

最简单的方法是让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

我遇到了这个问题,出于特定的原因,我需要显示&而不是&在文本区域中。为此,我将""通过"&amp"

我希望它能帮助

您可以使用encodeURIComponent()函数来解决问题。您只需更改代码如下。我认为您已经将textarea值设置为变量othr。您只能使用encodeURIComponent(othr)对该变量进行编码。这意味着您可以使用encodeURI Component方法解析文本区域值。

 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",