如何编写一个HTML JSON AJAX测试工具与美化,语法突出显示JSON结果

How to write an HTML JSON AJAX test harness with prettify, syntax highlighted JSON result?

本文关键字:JSON 语法 结果 显示 AJAX 何编写 HTML 一个 测试工具      更新时间:2023-09-26

我已经写了一个JSON API,但是我不会在视图上工作。

我如何测试JSON API与一个简单的网页与美化,语法突出显示JSON结果?

让我们使用以下GET API调用作为示例:

http://www.google.com/calendar/feeds/developer-calendar@google.com/public/full ? alt = json

注意:这个问题是指导性的,会有答案的。

这是整个HTML文件的内联javascript。

我在解决方案中使用了jQuery和highlight.js

我在Chrome上运行结果,我不相信它在IE中正常工作。

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/7.3/highlight.min.js"></script>
    <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/7.3/styles/default.min.css" />
    <script>
    $(document).ready(function() {
        hljs.initHighlightingOnLoad();
        $.ajax({
            url: "http://www.google.com/calendar/feeds/developer-calendar@google.com/public/full",
            dataType: "json",
            //contentType: "application/json; charset=utf-8", // NOTE: use this parameter when calling your host server, but doesn't work with this google api
            type: "GET",
            data : { alt: "json" },
            complete: function(xhr, textStatus) {
                // set status
                $("#status").html(textStatus);
                // set plaintext
                $("#result").val(xhr.responseText);
                // set prettytext
                var data = JSON.parse(xhr.responseText);
                var stringify = JSON.stringify(data, undefined, 2);
                var prettify = hljs.highlightAuto(stringify).value;
                prettify = hljs.fixMarkup(prettify);
                $("#prettyResult").html(prettify);
            }
        });
    });
    </script>
</head>
<body>
    <tt>Status: <span id="status">waiting ...</span></tt><br /><br />
    <textarea id="result" style="width: 1024px; height: 100px;"></textarea>
    <pre><code id="prettyResult" class="json" style="width: 1024px;"></code></pre>
</body>
</html>