在javascript中编码/解码html标签

Encode/decode html tags in javascript

本文关键字:解码 html 标签 编码 javascript      更新时间:2023-09-26

我有一个用nicEdit插件美化的文本区。

我需要通过ajax post发送代码结果到我的php服务器。我应该做些什么来转义html标签并在我的服务器中接收它们?

另外,我需要通过另一个ajax调用在另一个网页中显示它们。为了解码他们从php接收后,我应该怎么做呢?

这是我尝试过的json:

{'title':'srefzgseg','text':'<a href="link_to_page">s</a>drhgrdshgrdghrdgdgrdg<img src="http://www.joomlaworks.net/images/demos/galleries/abstract/7.jpg" alt="dgfvsegfseg" align="none">'}

我的函数:

function saveData(){
    var title = $("#titulo").val();
    var text = new nicEditors.findEditor('new_area').getContent();
    var jsonNew = "{'title':'"+title+"','text':'"+text+"'}";
    console.log(jsonNew);
    $.ajax({
        type: "POST",
        url: "./server/saveNewData.php",
        contentType: "application/json; charset=utf-8",
        data: jsonNew,
        dataType: "json",
        success: function(response) {
        },
        error:function(xhr, status, message) {console.log(message); alert("Ha ocurrido un error al guardar los datos");}
    });
}

您的JSON无效。JSON中的字符串应该有双引号。

如果在字符串中也需要双引号,则需要用反斜杠转义。

但是,与其自己编写解决方案,不如让JavaScript处理json序列化,这样就不会有这个问题了:

var o = {};
o.title = $("#titulo").val();
o.text = new nicEditors.findEditor('new_area').getContent();
var jsonNew = JSON.stringify(o);