我有一个表单中的文本区域,我正尝试使用 jQuery 通过 ajax 发送该表单。我的问题是当文本区域包含换行符和符号 (&) 时。
我使用以下js代码获取textarea的值:
// 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);
与textarea值如下:
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 将包含换行符和符号的 textarea 数据发送到 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发送
在服务器端
假设您的 json_decode`d 值保存在名为 $data 的变量中,请执行以下操作:
$val = str_replace( '__and__', '&', $data['value'] );
这样你就可以在不让你的 json_decode 失败的情况下保留和号
你可以用别的东西代替and作为占位符
虽然令人困惑的是它为什么会坏掉。
关于php - 如何通过包含 & 符号和/或换行符的 ajax 传递 textarea 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6229961/