$.getJSON request is behaving in a way I am unclear about. Not sure how to format the request with callback=?

限于喜欢 提交于 2019-12-08 13:09:21

问题


Of three jquery json requests, one of them is giving cross-domain errors because I don't know how to include the callback=? (or really why that denotes json vs jsonp).

Two requests to the same api, just one uses parameters and it's new to me on why it's not working (i've tried adding the &callback=? and other such solutions.)

Thanks!

http://jsfiddle.net/hCWwT/10/

var names = ["athenelive", "riotgames", "aphromoo"];

var obj = jQuery.parseJSON('{"name": {"life": "{life}","logo": "{logo}","status": "{status}","preview": "{preview}","url": "{url}"}}');

wtfJSON();

function wtfJSON() {

for (index = 0; index < names.length; ++index) {

    $.getJSON("https://api.twitch.tv/kraken/channels/" + names[index] + "/?callback=?", function (json) {

        $('body').append("Stufffff: " + obj.name.logo + "<br>");

        $('body').append("Name: " + json.name + "<br>");
        $('body').append("Logo: " + json.logo + "<br>");
        $('body').append("Status(title): " + json.status + "<br>");
        $('body').append("URL: " + json.url + "<br>");

    });

    $.getJSON("https://api.twitch.tv/kraken/streams/" + names[index] + "/?callback=?", function (json) {
        if (json.stream !== null) {

            $('body').append("Preview: " + json.stream.preview.medium + "<br>");

        }
    });

    $.getJSON("https://api.twitch.tv/kraken/channels/" + names[index] + "/videos?limit=3&broadcasts=true$callback=?", function (json) {

        $('body').append("Video Name: " + json + "<br>");

    });
}
}

回答1:


Look at your console:

XMLHttpRequest cannot load https://api.twitch.tv/kraken/channels/athenelive/videos?limit=3&broadcasts=true. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.

Using $.getJSON with a callback argument actually sends a JSONP request, which jQuery implements by just creating a <script> tag and using a unique global callback. Without it, you attempt to send a regular AJAX request to that other website, which isn't allowed by your browser.

Add a callback parameter and it'll work:

$.getJSON("https://api.twitch.tv/kraken/channels/" + names[index] + "/videos?limit=3&broadcasts=true&callback=?", function (json) {


来源:https://stackoverflow.com/questions/17645614/getjson-request-is-behaving-in-a-way-i-am-unclear-about-not-sure-how-to-forma

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