在 HTMl 上,我有一个 textarea(评论框)(id = #comment")
,它可以包含多行。当我使用 ajax 发送它时,我没有问题。虽然在检索时此数据,JSON 数据不再有效(以下是 json 的一小部分摘录:
"items" : [ {
...<<other values>>...,
"comment": "Approved!!!!
Or Not
Or Did I
Approve this....."
,...<<other values>>...}
所以我假设在将文本区域发送到服务器时我必须转换它的值。 但是当我尝试使用 JSON.Parse 时出现错误:
$.ajax({
type: "POST",
url: "updateitem.aspx",
data: {
myId: $("body").attr("id"),
comment: JSON.parse($("#comment").val()),
}
...
})
但这会导致错误:
SyntaxError: JSON.parse: unexpected keyword at line 1 column 1 of the JSON data
comment: JSON.parse($("#comment").val()),
所以我的问题实际上是:如何将数据从文本区域发送到服务器。同时保留任何非 JSON 字符和换行符。解决方案可能很简单,但我似乎唯一找到的是:Past JSON in textarea
、ReplaceAll
(可以工作,但我正在寻找更好的解决方案)
尝试了以下解决方案但无济于事。 how-can-i-pass-textarea-data-via-ajax-that-contains-ampersands-and-or-linebreaks
最佳答案
您需要使用 JSON.stringify
为此:
var comment = JSON.stringify($("#comment").val());
// Now comment is a JSON string to send to your server
$.ajax({
type: "POST",
url: "updateitem.aspx",
data: {
myId: $("body").attr("id"),
comment: comment,
}
...
})
请参阅 jsfiddle:http://jsfiddle.net/14cjojhq/1/
关于javascript - JSON:处理文本区域中的换行符(和其他无效的 JSON 字符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25400069/