Jquery escapes "<" " >"

Jquery escapes "<" " >"

本文关键字:quot gt lt escapes Jquery      更新时间:2023-09-26

我有一个文本区。在其单击事件上。我在DB插入它,然后显示它作为元素列表中的第一个元素。问题是。如果在textarea中输入"<afasd>", jquery无法正常显示。它显示为空。代码是

var note = $.trim( $('#rep_notes_add_notes').val());
    if(note == "")
    return false;
    $.ajax({
                url: 'include/tre.ajax.php',
                type: 'POST',
                data: {
                    action: 'insert',
                    note: note
                    },
                dataType: 'json',
                success: function(data) {
                    jQuery("#rep_notes_add_notes").val('');
                    jQuery(".no_notes").remove();
                    *$(".notes:eq(0)").before('<div class="notes">'+note+'<div class="note-added"> Added by  '+user +'<span> on </span>'+data.update_time+'</div></div>');*
                }
            });

标记为*的行找到注释div,然后在它之前插入一个元素以显示新输入的文本。

有人能帮我解决这个问题吗?

它不显示它,因为它认为<afasd>是一个标记,而不是文本。需要将"<"修改为"&lt;"才能显示。

var str = "<afasd>";
var escaped = str.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");

不要将任意数据连接到HTML中。您将面临注入问题,以及您所看到的无效HTML问题。这条线:

$(".notes:eq(0)").before('<div class="notes">'+note+'<div class="note-added"> Added by  '+user +'<span> on </span>'+data.update_time+'</div></div>');

应该是这样的(未测试,未完成,但你明白的意思):

$('.notes:eq(0)').before(
    $('<div>').addClass('notes').text('Added by ' + user)
);
关键是,如果你想设置文本,使用.text(),而不是HTML。