При загрузке данных в летнюю заметку JS выдает ошибку неожиданного идентификатора - PullRequest
1 голос
/ 01 ноября 2019

Я использую летнюю заметку в качестве текстового редактора в качестве замены wp-редактора для создания постов. Когда создается сообщение через летнюю заметку и отправляется на сервер, оно успешно создается, но когда я хочу отредактировать одно и то же сообщение (, состоящее из одинарной или двойной кавычки ), JS показывает ошибкунеожиданного идентификатора и останавливает загрузку кода. Ниже я делюсь своим кодом, который я пытался редактировать за последние 5 дней, но теперь я сдаюсь и не могу понять, где я ошибаюсь.

----------- Это блок кода, который я использую для создания поста, я буду публиковать HTML, Jquery, ajax и код PHP -----------

HTML:

<div class="col-md-9">
   <textarea name="post_content" id="post_content" class="form-control round post_content summernote"></textarea>
</div>

jQuery код:

function clean_html(editor, type, value)
{
    if (value.indexOf("<"+type+">") >= 0)
        {
            if(type == "b")
                {
                    marca = /<b(?:.*?)>(?:.*?)<\/b>/g;
                    replaceIniTag = "<strong>";
                    replaceEndTag = "</strong>";
                }
            else
                {
                    marca = /<i(?:.*?)>(?:.*?)<\/i>/g;
                    replaceIniTag = "<em>";
                    replaceEndTag = "</em>";
                }
            var matches = value.match(marca), 
            len = matches.length,
            i;
            for (i = 0; i < len; i++)
                {
                    str = $(matches[i]).text();
                    str = replaceIniTag+str+replaceEndTag;
                    value = value.replace(matches[i], str);
                }
            $('#post_content').summernote('code', value); //Replace the editor content
        }
}

function CleanPastedHTML(input)
{
    // 1. remove line breaks / Mso classes
    var stringStripper = /(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;
    var output = input.replace(stringStripper, ' ');
    // 2. strip Word generated HTML comments
    var commentSripper = new RegExp('<!--(.*?)-->','g');
    var output = output.replace(commentSripper, '');
    var tagStripper = new RegExp('<(/)*(meta|link|span|\\?xml:|st1:|o:|font)(.*?)>','gi');
    // 3. remove tags leave content if any
    output = output.replace(tagStripper, '');
    // 4. Remove everything in between and including tags '<style(.)style(.)>'
    var badTags = ['style', 'script','applet','embed','noframes','noscript'];

    for (var i=0; i< badTags.length; i++)
        {
            tagStripper = new RegExp('<'+badTags[i]+'.*?'+badTags[i]+'(.*?)>', 'gi');
            output = output.replace(tagStripper, '');
        }
    // 5. remove attributes ' style="..."'
    var badAttributes = ['style', 'start'];
    for (var i=0; i< badAttributes.length; i++)
        {
            var attributeStripper = new RegExp(' ' + badAttributes[i] + '="(.*?)"','gi');
            output = output.replace(attributeStripper, '');
        }
    return output;
}

$('#post_content').summernote(
{
    height: 200,
    focus: false,
    disableDragAndDrop: true,
    popover: {
                image: [],
                link: [],
                air: []
              },
    // disableResizeEditor: true,
    placeholder: "Type Your Post Content...",
    toolbar: [
                ['cleaner',['cleaner']], // The Button
                ['style', ['style']],
                // ['style', ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'clear']],
                ['style', ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript']],
                // ['fontname', ['fontname']],
                ['fontsize', ['fontsize']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['height', ['height']],
                ['table', ['table']],
                ['insert', ['link', 'hr']],
                // ['insert', ['link', 'picture', 'video', 'hr', 'readmore']],
                ['view', ['fullscreen', 'codeview']]
                // ['help', ['help']]
            ],
    cleaner:{
                  action: 'both', // both|button|paste 'button' only cleans via toolbar button, 'paste' only clean when pasting content, both does both options.
                  newline: '<br>', // Summernote's default is to use '<p><br></p>'
                  notStyle: 'position:absolute;top:0;left:0;right:0', // Position of Notification
                  icon: '<i class="note-icon-row-remove"></i> &nbsp;Clean',
                  keepHtml: false, // Remove all Html formats
                  keepOnlyTags: ['<p>', '<br>', '<ul>', '<li>', '<b>', '<strong>','<i>', '<a>'], // If keepHtml is true, remove all tags except these
                  keepClasses: false, // Remove Classes
                  badTags: ['style', 'script', 'applet', 'embed', 'noframes', 'noscript', 'html'], // Remove full tags with contents
                  badAttributes: ['style', 'start'], // Remove attributes from remaining tags
                  limitChars: false, // 0/false|# 0/false disables option
                  limitDisplay: 'both', // text|html|both
                  limitStop: false // true/false
            },
        callbacks:
            {
                onPaste: function (e)
                    {
                        var thisNote = $(this);
                        var updatePastedText = function(someNote)
                            {
                                var original = someNote.code();
                                var cleaned = CleanPastedHTML(original); //this is where to call whatever clean function you want. I have mine in a different file, called CleanPastedHTML.
                                someNote.code('').html(cleaned); //this sets the displayed content editor to the cleaned pasted code.
                            };
                        setTimeout(function ()
                            {
                                //this kinda sucks, but if you don't do a setTimeout, 
                                //the function is called before the text is really pasted.
                                updatePastedText(thisNote);
                            }, 10);
                    },
                onChange: function(contents, $editable)
                    {
                        clean_html(this, "b", contents);
                        clean_html(this, "i", contents);
                    }
            }
});

$('#post_content').summernote('removeModule', 'autoLink');

AJAX код:

var post_content = $("#post_content").summernote('code');

$.ajax({
    url: '/bypasser/modules/create.php',
    type: 'POST',
    dataType: 'JSON',
    data: {action: "create", type: "post", title: post_title, slug: post_slug, category: post_category_id, content: post_content, excerpt: post_excerpt, tags: post_tags, featured_image: response, original_image: $original_image, status: post_status},
    success:function(resp)
        {
            if(resp.status == "success")
                {
                    $("#post_title, #post_slug, #post_content, select.post_category, #post_excerpt, #post_tags, #upload_image, #post_status, #post_preview, #post_create").attr("disabled", false);
                    $('#post_content').summernote('enable');
                    $('#post_content').summernote('reset');
                }
        }
});

Код PHP: (я удалил остальной код, так как он был нежелательным)

$query = "
        INSERT INTO posts(
                            content,
                            created,
                            modified
                          )
        VALUES(
                '".htmlentities($_POST['content'], ENT_QUOTES)."',
                '".$created."',
                '".$modified."'
            ) ";

Когда я редактирую пост, оставшийся выше код - это то же самое, что я долженпоместите значения в летнюю заметку, так что я должен достичь этого с помощью JS, а ниже приведен код. Код в теге <script> загружается в файл PHP, тогда как другой код находится в файле .js

<script>
   var htmlCode = "<?php echo htmlspecialchars_decode($content); ?>";
</script>

$('#post_content').summernote('code', htmlCode);

. Проблема в том, что если у вас нет single quote or double quote,код работает нормально, но если у вас есть a single quote or double quote, то при загрузке страницы выдается ошибка SyntaxError: Unexpected identifier /bypasser/edit?page=post&id=58:450, которая при проверке приводит к этой строке

var htmlCode = "<?php echo htmlspecialchars_decode($content); ?>";

Ниже приводится содержание, опубликованное после проверки:

<script>
    var htmlCode = "<p>Whatsapp for iOS now lets users completely ignore muted chat. Also, the recently now added group privacy options. </p><p> I<span style="font-size: 1rem;">ndian users of Fitbit least active and most sleep deprived - Fitbit the wearables brand. </span></p><p><span style="font-size: 1rem;"> Apple&rsquo;s latest AirPods Pro launched in India at Rs. 24,900 with active noise cancellation.&nbsp;</span><span style="font-size: 1rem;">The truly wireless pair of earphones will be available with Apple&rsquo;s authorised resellers.</span></p><p><span style="font-size: 1rem;"> Google to secure G Pay transactions with biometrics. The latest 2.100 version shows facial recognition and fingerprint features. </span></p><p><span style="font-size: 1rem;">  MTNL users get two 1Gbps plans, for 2,990 and 4,990. The plans are now restricted to Delhi. </span></p><p><span style="font-size: 1rem;">Jio All-in-one plans start at Rs.222 post introduction of 6ps/min call charges for Jio to non-Jio calls.&nbsp;</span></p>";
</script>

Я застрял в этой проблеме за последние 5 дней и не могу понять, что нужно сделать. Кто-нибудь может направить меня, где я иду не так?

...