简体   繁体   English

使用JSONP从另一台服务器获取JSON数据

[英]Using JSONP to get JSON data from another server

I'm trying to collect JSON data from a website hosted by a company. 我正在尝试从公司托管的网站收集JSON数据。 I am not on the same domain, so I can't just access it. 我不在同一个域,所以我不能只访问它。 From the headers, it seems that they don't use CORS either. 从标题看,它们似乎也不使用CORS。 So I've tried to use JSONP to parse the data, but it doesn't seem to work. 所以我尝试使用JSONP来解析数据,但它似乎不起作用。 I've tried doing $.getJSON and $.ajax, but those throw errors and don't call the function. 我已经尝试过$ .getJSON和$ .ajax,但是那些抛出错误并且不调用函数。 This is my solution thus far, and in the response from the server, it still doesn't wrap the data in getResults. 这是我迄今为止的解决方案,在服务器的响应中,它仍然没有将数据包装在getResults中。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<script type="text/javascript" src="jquery/js/jquery-1.9.0.min.js"></script>

<script>
function getResults(data) {
    console.log(data[0].name);
}
</script>
<script type='text/javascript' src='https://solstice.applauncher.com/external/contacts.json?callback=getResults'></script>

I'm fairly new to HTML, JavaScript, and jQuery, so I'm just really confused why the response is being wrapped in the function and console log isn't working. 我是HTML,JavaScript和jQuery的新手,所以我真的很困惑为什么响应被包装在函数中并且控制台日志不起作用。 Any help would be appreciated. 任何帮助,将不胜感激。

You can use many ways but the two most convenient ones are either an AJAX call or to use jQuery's getJSON() method 您可以使用多种方法,但两个最方便的方法是AJAX调用或使用jQuery的getJSON()方法

Using AJAX call 使用AJAX调用

$(document).ready(function() {
  $(".btn").click(function() {
    $.ajax({type: "get",
            url: "http://api.forismatic.com/api/1.0/",
            data: {method: "getQuote",format: "jsonp",lang: "en"},
            dataType: "jsonp",
            jsonp: "jsonp",
            jsonpCallback: "myJsonMethod"
    }); 
  });
});
function myJsonMethod(response){
  console.log (response);
}

In the above method response Object has all the JSON data from the API call. 在上面的方法中, response Object包含来自API调用的所有JSON数据。

Using getJSON() 使用getJSON()

$(document).ready(function() {
  $(".btn").click(function() {
    $.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=myJsonMethod&?callback=?");
  });
});
function myJsonMethod(response){
  console.log (response);
}

In the above method the same thing happens. 在上面的方法中,同样的事情发生了。

NOTE --> That JSONP takes the name of the callback function on which the response is to be sent. 注 - > JSONP采用要在其上发送响应的回调函数的名称。

JSONP is a technique by which you put your request into a script tag URL (which is allowed to any domain) and you pass in that URL a parameter which indicates the name of a function that you want the resulting script that is returned to call and pass it your data. JSONP是一种技术,通过它您可以将请求放入脚本标记URL(允许任何域),并在该URL中传入一个参数,该参数指示您希望返回调用的结果脚本的函数名称。传递你的数据。 In this case it looks like you're specifying that the callback function is named getResults . 在这种情况下,您似乎指定回调函数名为getResults

For JSONP to work, the server you are sending the request to must specifically support it because it requires a specific type of response format and it enables any domain from any browser to make the request which isn't something all sites want to enable. 要使JSONP正常工作,您发送请求的服务器必须专门支持它,因为它需要特定类型的响应格式,并且它允许来自任何浏览器的任何域发出请求,这不是所有站点都想要启用的。

So, the very first thing you need to find out is if the server you're requesting data from supports JSONP or not and if so, make sure you understand exactly how it will format the response and how it is expecting the callback function to be specified (common convention is with the callback=xxx URL parameter, but it doesn't have to be done that way. 因此,您需要了解的第一件事是,您要求数据的服务器是否支持JSONP,如果是,请确保您确切了解它将如何格式化响应以及它如何期望回调函数是指定(常见约定是使用callback=xxx URL参数,但不一定要这样做。

If the server you want data from does not support JSONP, then you simply can't use JSONP to get data from it. 如果您想要数据的服务器不支持JSONP,那么您根本无法使用JSONP从中获取数据。 If it doesn't support some other cross domain request strategy, then you can't get data from it via a browser web page and will have to do the request from something other than a browser (like another server). 如果它不支持某些其他跨域请求策略,那么您无法通过浏览器网页从中获取数据,并且必须从浏览器以外的其他内容(如其他服务器)执行请求。

JSONP is a method that the server has to implement. JSONP是服务器必须实现的方法。

If you are sure the server accepts and understands JSONP, then maybe the parameter you use to pass the callback name is not callback . 如果您确定服务器接受并理解JSONP,那么您用来传递回调名称的参数可能不是callback See their documentation if they have one. 如果有文档,请查看他们的文档。

Otherwise, you simply can't get the json data from a browser. 否则,您无法从浏览器获取json数据。

live sample from here : 来自这里的现场样本:

JSONP - JSON with padding, ie. JSONP - 带填充的JSON,即。 javascript object wrapped in a callback, in our case it's jsonCallback javascript对象包含在回调中,在我们的例子中是jsonCallback

this is content of file: 这是文件的内容:

jsonCallback(
    {
        "sites":
        [
            {
                "siteName": "JQUERY4U",
                "domainName": "http://www.jquery4u.com",
                "description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips &amp; Code Snippets."
            },
            {
                "siteName": "BLOGOOLA",
                "domainName": "http://www.blogoola.com",
                "description": "Expose your blog to millions and increase your audience."
            },
            {
                "siteName": "PHPSCRIPTS4U",
                "domainName": "http://www.phpscripts4u.com",
                "description": "The Blog of Enthusiastic PHP Scripters"
            }
        ]
    }
);

code for retrieving a file: 用于检索文件的代码:

(function($) {
var url = 'http://www.jquery4u.com/scripts/jquery4u-sites.json?callback=?';

$.ajax({
   type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback', <-- callback here
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(json) {
       console.dir(json.sites);
    },
    error: function(e) {
       console.log(e.message);
    }
});

})(jQuery);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM