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

混江龙づ霸主 提交于 2019-12-08 08:06:09

问题


I've written a JSON API, but I won't be working on the views.

How do I test the JSON API with a simple webpage with prettify, syntax highlighted JSON result?

Let's use the following GET API call as an example:

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

NOTE: this question is meant to be instructional, answer will be provided. I searched and didn't find a similar answer.


回答1:


Here's the entire HTML file with in-line javascript.

I used jQuery and highlight.js in the solution.

I ran the result on Chrome, I don't believe it works properly in 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>


来源:https://stackoverflow.com/questions/15165434/how-to-write-an-html-json-ajax-test-harness-with-prettify-syntax-highlighted-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!