效果:
HTML:
<script src="https://codemirror.net/lib/codemirror.js"></script>
<script src="https://codemirror.net/mode/javascript/javascript.js"></script>
<link rel="stylesheet" href="https://codemirror.net/lib/codemirror.css">
<div id="fn"></div>
<button class="btn btn-sm btn-success offset2" id="fn-save-btn">保存</button>
<button class="btn btn-sm btn-success" id="fn-eval-btn">运行</button>
<div id="eval-result" class="eval-result"></div>
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(`<div>运行结果:</div><code>${result.data}</code>`)
} else {
alert(result.errorMessage)
}
}
, error: (err) => {
alert(JSON.stringify(err))
}
});
});// fn-eval-btn
后端代码 Kotlin:
@PostMapping("/evalJs.json")
@ResponseBody
fun evalJs(js: String): ResultVo<String> {
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 的语法)。