javascript - JSON:处理文本区域中的换行符(和其他无效的 JSON 字符)

标签 javascript jquery json

在 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 textareaReplaceAll(可以工作,但我正在寻找更好的解决方案)

尝试了以下解决方案但无济于事。 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/

相关文章:

php - 在网站上显示 JSON 数据

c# - 如何在 JSONP 响应中管理 '?

java - 使用 JSON 参数简化 REST URL

javascript - 如何在保持分隔符的同时根据空格或符号拆分字符串?

javascript - react : Unable to access child props in parent's event handler

javascript - 在使用jquery在鼠标悬停时淡入之前。如何让隐藏元素占用空间?

javascript - css3 转换不是第一次在 Firefox 4 中触发

javascript - 比较 2 个数组以输出总整数

javascript - 为 promise 设置计时器

php - Ajax PHP JavaScript : error when using POST method