在url中访问JSON

时间:2015-10-26 03:04:27

标签: javascript jquery html json html5

所以我不确定如何做到这一点,但我想在此网址中获取JSON,然后将article.articleText附加到id为输出的<div>

http://api.trove.nla.gov.au/newspaper/2184103?key=jja10ssv4950uh65&encoding=json&include=articletext

编辑以显示我尝试过的内容:

var apiKey = "jja10ssv4950uh65"; 
                $("#searchbtn").click(function(e) {
                    e.preventDefault();
                    var searchTerm = getRandomVideo();
                    var url = "http://api.trove.nla.gov.au/newspaper/" + searchTerm + "?key=" + apiKey + "&encoding=json&include=articletext"

                    $.getJSON(url, function(data) {
                        $('#output').empty();
                        $("#output").append("<p>" + data.article.articleText +"</p>");
                    });
                });

1 个答案:

答案 0 :(得分:0)

  

XMLHttpRequest无法加载http://api.trove.nla.gov.au/newspaper/2184103?key=jja10ssv4950uh65&encoding=json&include=articletext。请求的资源上不存在Access-Control-Allow-Origin标头。起源&#39; http://localhost&#39;因此不允许访问。

为此,您需要将标题添加到您的响应正文中,以便可以访问它。

使用JSONP

的替代解决方案
var apiKey = "jja10ssv4950uh65"; 

$("#searchbtn").click(function(e) {
    e.preventDefault();
    var searchTerm = getRandomVideo();
    var url = "http://api.trove.nla.gov.au/newspaper/" + searchTerm + "?key=" + apiKey + "&encoding=json&include=articletext";

    $.ajax({
        url: url,
        dataType: 'JSONP',
        jsonpCallback: 'callback',
        type: 'GET',
        success: function (data) {
            $('#output').empty();
            console.log(data);
            $("#output").append("<p>" + data.article.articleText +"</p>");
        }
    });
});