How to write an HTML JSON AJAX test harness with p

2019-05-31 16:13发布

问题:

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>