CodeMirror 代码渲染神器的极简入门实例

效果:

CodeMirror 代码渲染神器的极简入门实例_第1张图片
image.png

HTML:




JS 代码示例:

// 渲染代码:
var editor = CodeMirror.fromTextArea(document.getElementById("fnBody"), {
                lineNumbers: true,
                mode: "javascript",
                matchBrackets: true
 });
// 获取代码的文本值
var fnBody = editor.doc.getValue();


// 运行脚本,预览结果
$('#fn-eval-btn').unbind().bind('click', () => {
    console.dir(editor);
    var fnBody = editor.doc.getValue();
    var postData = {
        js: fnBody
    };

    $.ajax({
        url: '/datafactory/evalJs.json'
        , data: postData
        , type: 'POST'
        , success: (result) => {
            if (result.success == true) {
                $('#eval-result').html(`
运行结果:
${result.data}`) } else { alert(result.errorMessage) } } , error: (err) => { alert(JSON.stringify(err)) } }); });// fn-eval-btn

后端代码 Kotlin:

@PostMapping("/evalJs.json")
@ResponseBody
fun evalJs(js: String): ResultVo {
    println("js=${js}")

    val result = ResultVo(
            data = "",
            isSuccess = false,
            errorCode = "1",
            errorMessage = "",
            state = "1"
    )

    try {
        val data = NashornUtil.evalJs(js)
        result.data = data
        result.isSuccess = true
        result.errorCode = "0"
        result.errorMessage = ""
        result.state = ""
    } catch (e: Exception) {
        result.errorMessage = e.message ?: ""
    }
    return result
}

其中,evalJs() 的函数实现如下:

package com.alibaba.xxpt.qa.adt.util

import javax.script.ScriptEngineManager

object NashornUtil {
    private val scriptEngineManager = ScriptEngineManager()
    private val nashorn = scriptEngineManager.getEngineByName("nashorn")


    fun evalJs(js: String): String {
        try {
            return nashorn.eval(js).toString()
        } catch (e: Exception) {
            e.printStackTrace()
            return ""
        }
    }
}

使用的是 Java 8 中的nashorn 引擎(支持 ES5 的语法)。

参考文档:https://codemirror.net/

你可能感兴趣的:(CodeMirror 代码渲染神器的极简入门实例)