在夏季注释中加载数据时 JS 弹出 Unexpected Identifier 的错误

Posted

技术标签:

【中文标题】在夏季注释中加载数据时 JS 弹出 Unexpected Identifier 的错误【英文标题】:While loading the data in summer note JS is popping an error of Unexpected Identifier 【发布时间】:2020-02-27 13:27:24 【问题描述】:

我使用 Summer note 作为文本编辑器来代替 wp-editor 来创建帖子。当通过夏季注释创建帖子并将其发送到服务器时,它已成功创建,但是当我想编辑同一个帖子(由单引号或双引号组成)时,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 来实现它,下面是代码。 &lt;script&gt; 标签中的代码被加载到 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&amp;id=58:450 的ann 错误,检查时会出现此行

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 天里,我一直被这个问题困扰,无法弄清楚应该做什么。谁能指导我哪里出错了?

【问题讨论】:

&lt;?php echo htmlspecialchars_decode($content); ?&gt;打印的内容是什么? 我已经编辑了带有打印内容的帖子,请看一下。 @VLAZ 你能帮帮我吗? 【参考方案1】:

我希望这可以帮助某人,您可以使用反引号(`)字符来允许单引号和双引号,我不确定当您的字符串也包含反引号时这会如何表现,但到目前为止我一直在使用它。 这通常对我有用,希望对你有帮助

    var htmlFromDatabase = `<?php echo $topic['topicContent']; ?>`
    $("#topicContent").summernote('code', htmlFromDatabase);

【讨论】:

以上是关于在夏季注释中加载数据时 JS 弹出 Unexpected Identifier 的错误的主要内容,如果未能解决你的问题,请参考以下文章

在 React.js 中加载异步数据时防止 UI 闪烁

easyui中加载两个对话框画面显示错误

在 jqGrid 列中加载图像

如何在按钮单击事件中的模式弹出扩展器中的iframe中加载页面?

在 Node js 应用程序 + MongoDb 中加载数据时出现错误

如何用PowerDesigner 逆向工程导出数据库 表+字段+注释