折腾:
期间,虽然输出了被格式化后的json字符串,但是不够美观。
想到看看是否可以去高亮显示。
然后再想办法去代码高亮:
jquery bootstrap pre highlight
下载下来

放到项目中,去使用
然后默认的效果不够好:
所以去找找其他theme主题的效果
找到了官网点击style后,可以切换不同效果,找到这个还可以:
atom-one-dark

language: json
style: monokai-sublime

分别效果是:


【总结】
此处,是用
去高亮json代码。
做法:
下载:
到:
一个highlight.js
很多个style/theme的css,包括default.css和其他的
然后放到项目中:

加到代码中:
html中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <!-- <link rel= "stylesheet" href= "css/highlightjs_default.css" > --> <link rel= "stylesheet" href= "css/highlight_atom-one-dark.css" > <!-- <link rel= "stylesheet" href= "css/highlight_monokai-sublime.css" > --> <link rel= "stylesheet" href= "css/main.css" > < /head > <div id = "response" class= "bg-light box-shadow mx-auto" > <p id = "responseText" >here will output response< /p > < /div > <script src= "js/bootstrap.js" >< /script > <script src= "js/highlight.js" >< /script > <script src= "js/main.js" >< /script > < /body > < /html > |
static/js/main.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | $(document).ready(function(){ / / when got response json, update to highlight it function updateHighlight() { console.log( "updateHighlight" ); $( 'pre code' ).each(function(i, block) { hljs.highlightBlock(block); }); } $( "#submitInput" ).click(function(event){ event.preventDefault(); ajaxSubmitInput(); }); function ajaxSubmitInput() { console.log( "ajaxSubmitInput" ); var inputRequest = $( "#inputRequest" ).val(); console.log( "inputRequest=%s" , inputRequest); var encodedInputRequest = encodeURIComponent(inputRequest) console.log( "encodedInputRequest=%s" , encodedInputRequest); console.log( "qaUrl=%s" , qaUrl); var fullQaUrl = qaUrl + "?input=" + encodedInputRequest console.log( "fullQaUrl=%s" , fullQaUrl); $.ajax({ type : "GET" , url : fullQaUrl, success: function(respJsonObj){ console.log( "respJsonObj=%o" , respJsonObj); / / var respnJsonStr = JSON.stringify(respJsonObj); / / var beautifiedJespnJsonStr = JSON.stringify(respJsonObj, null, '\t' ); var beautifiedJespnJsonStr = JSON.stringify(respJsonObj, null, 2 ); console.log( "beautifiedJespnJsonStr=%s" , beautifiedJespnJsonStr); var prevOutputValue = $( '#responseText' ).text(); console.log( "prevOutputValue=%o" , prevOutputValue); / / $( '#output' ).empty(); var afterOutputValue = $( '#responseText' ).html( '<pre><code class="json">' + beautifiedJespnJsonStr + "</code></pre>" ); console.log( "afterOutputValue=%o" , afterOutputValue); updateHighlight(); }, error : function(err) { $( "#output" ).html( "<strong>Error</strong>" ); console.log( "GET: " , qaUrl, " ERROR: " , err); } }); } }); }); |
js中的逻辑是:
点击提交按钮后,调用api接口,返回json对象,转化成带缩进的json字符串,放到p元素中去,前后加上:
<prev><code> your json string </code></pre>
且注意调用了:updateHighlight
否则由于json是后来加载的,不会被高亮的。
效果:

转载请注明:在路上 » 【已解决】js中如何把输出的json代码高亮显示