如何通过包含与号和/或换行符的ajax传递文本区域数据


How can I pass textarea data via ajax that contains ampersands and/or linebreaks?

我在一个表单中有一个文本区域,我正试图用jQuery通过ajax发送它。我的问题是当文本区域包含换行符和与号(&)时。

我用以下js代码获得文本区域的值:

// Find all the fields with class dirty
$('#customer .dirty').each(function() {
    fieldName = $(this).attr('id');
    fieldValue = $(this).val();
    // Create an object of dirty field names and values             
    var fields = { 'fieldName' : fieldName, 'value' : fieldValue }; 
    // Add the object of field names and values to the custRecordToUpdate array                 
    custRecordToUpdate.push(fields);  // note: this was initialized before  
});

var arrayToSend = {
    customer : custRecordToUpdate
};
var dataToSend = JSON.stringify(arrayToSend);

文本区域值如下:

1/8 CLEAR MIRROR  
3/8 CLEAR GLASS

如果我console.log(dataToSend),我会得到以下内容:

{"customer":[{"fieldName":"cust_note","value":"1/8 CLEAR MIRROR'n3/8 CLEAR GLASS"}]} 

在PHP脚本上,我json_decode发布的数据,它可以正常工作。

如果我将文本区域更改为包含一个与号,如下所示:

1/8 CLEAR MIRROR  
3/8 CLEAR GLASS & GLASS  

json_decode失败console.log(dataToSend)显示以下内容:

{"customer":[{"fieldName":"cust_note","value":"1/8 CLEAR MIRROR'n3/8 CLEAR GLASS & GLASS"}]}

json_last_error()显示语法错误

如果我将上面的js代码更改为:

fieldValue = encodeURIComponent($(this).val());

然后console.log(dataToSend)显示:

{"customer":[{"fieldName":"cust_note","value":"1%2F8%20CLEAR%20MIRROR%0A3%2F8%20CLEAR%20GLASS"}]}  

json_decode失败,两种数据情况都有语法错误

那么,如何通过ajax将包含换行符和符号的文本区域数据发送到php后端,并使json_decode不会失败呢?

解决方案:

根据下面的一些评论,我决定更改发送数据的ajax代码,这解决了问题,尽管我不知道为什么。

不管怎样,这是代码,以防它能帮助其他人。

var returnedHTML = $.ajax({
   type: "POST",
   url: 'index.php/customer/save_edit_customer',
   //data : "data="+dataToSend, // This is how I was sending it before 
   data : { "data" : dataToSend }, // This is the new code that works!
   async: false,
   cache: false
}).responseText;

假设您的文本保存在变量textareaText中执行此

var val = textareaText.replace('&', '__and__');

将其作为ajax 发送

在服务器端

假设您的jsondecode`d值保存在名为$data的变量中,请执行以下操作:

$val = str_replace( '__and__', '&', $data['value'] );

通过这种方式,你将能够保持安培数,而不会让你的jsondecode失败

您可以使用其他东西而不是作为占位符

尽管令人困惑的是它为什么会断裂。

我不确定你的对象应该是什么形状,但如果我改变它,它对我有效:

{"customer":[{"fieldName":"cust_note","value":"1/8 CLEAR MIRROR'n3/8 CLEAR GLASS & GLASS"}]}

{"customer":{"fieldName":"cust_note","value":"1/8 CLEAR MIRROR'n3/8 CLEAR GLASS & GLASS"}}

即从json对象中删除数组语法。

这是我的测试。。。

    var customer = {"customer":{"fieldName":"cust_note","value":"1/8 CLEAR MIRROR'n3/8 CLEAR GLASS & GLASS"}};
    alert(customer.customer.fieldName);
    alert(customer.customer.value);

这表明&不是你的问题,但[]是。