Javascript 从 URL 获取 JSON 文件并显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11456862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get a JSON file from URL and display
提问by LINGS
The code is very simple, I do not know why it deosnt work.
代码很简单,我不知道为什么它不起作用。
This is the link to the JSON file, http://webapp.armadealo.com/home.json
这是 JSON 文件的链接,http://webapp.armadealo.com/home.json
Here is the code using getJSON
这是使用 getJSON 的代码
$.getJSON("http://webapp.armadealo.com/home.json", function(data){
alert(data);
});
I just want the code to display the whole JSON content.
我只希望代码显示整个 JSON 内容。
采纳答案by LINGS
After so many months of search, I found the solution. Hence, I am answering my own question.
经过这么多个月的搜索,我找到了解决方案。因此,我正在回答我自己的问题。
When JSON is not supported and when we are stuck with Same Origin Policy, we have to wrap around our JSON with a padding and make it a JSONP.
当不支持 JSON 并且我们坚持使用同源策略时,我们必须用填充将我们的 JSON 包裹起来并使其成为 JSONP。
To do that, we have a life saving website http://anyorigin.com/
为此,我们有一个救生网站http://anyorigin.com/
You can paste your URL and get the corresponding JQuery code something like this,
您可以粘贴您的 URL 并获取相应的 JQuery 代码,如下所示,
$.getJSON('http://anyorigin.com/get?url=http%3A//webapp.armadealo.com/home.json&callback=?', function(data){
$('#output').html(data.contents);
});
If you want to use your own code, then just use the URL from the code above, which is
如果您想使用自己的代码,那么只需使用上面代码中的 URL,即
http://anyorigin.com/get?url=http%3A//webapp.armadealo.com/home.json&callback=?
This above URL will give you the same JSON data as JSONP and solves all the trouble.
上面的 URL 将为您提供与 JSONP 相同的 JSON 数据并解决所有麻烦。
I had used the following code, which on success calls displayAll function
我使用了以下代码,成功调用 displayAll 函数
$.ajax({
url: 'http://anyorigin.com/get?url=http%3A//webapp.armadealo.com/home.json&callback=?',
type: 'GET',
dataType: "json",
success: displayAll
});
function displayAll(data){
alert(data);
}
回答by Brian Nickel
If you look in Chrome inspector, you probably see this error:
如果您查看 Chrome 检查器,您可能会看到以下错误:
XMLHttpRequest cannot load http://webapp.armadealo.com/home.json. Origin http://stackoverflow.comis not allowed by Access-Control-Allow-Origin.
XMLHttpRequest 无法加载http://webapp.armadealo.com/home.json。Access-Control-Allow-Origin 不允许Origin http://stackoverflow.com。
What this means is that the server doesn't want the client web page reading the file. The client isn't trusted. This is a basic security feature of XMLHttpRequest in order to prevent a site like mybank.evil.com from downloading data from mybank.com. It unfortunately makes testing from a local file challenging.
这意味着服务器不希望客户端网页读取文件。客户端不受信任。这是 XMLHttpRequest 的一项基本安全功能,目的是防止像 mybank.evil.com 这样的站点从 mybank.com 下载数据。不幸的是,它使从本地文件进行的测试具有挑战性。
If you trust anysite with your data or a select number of sites, you can configure your server script to send the Access-Control-Allow-Origin
to allow certain sites through.
如果您信任任何站点的数据或选定数量的站点,您可以配置您的服务器脚本以发送Access-Control-Allow-Origin
允许某些站点通过。
See https://developer.mozilla.org/en/http_access_controlfor more details.
有关更多详细信息,请参阅https://developer.mozilla.org/en/http_access_control。
回答by yesh
From what I could tell is that your server doesn't support JSONP with their requests. For instance
据我所知,您的服务器不支持 JSONP 的请求。例如
var getUrl = 'http://webapp.armadealo.com/home.json';
$.ajax({
url : getUrl,
type : 'GET',
dataType : 'jsonp text',
jsonp: 'jsonp',
crossDomain : true,
success: function() { console.log('Success!'); },
error: function() { console.log('Uh Oh!'); },
});
This would say SyntaxError: invalid label
. The return as you have it is not properly formatted JSONP. It has to be wrapped to work as JSONP because jQuery requires it.
这会说SyntaxError: invalid label
。您所拥有的返回格式不正确 JSONP。它必须被包装起来才能作为 JSONP 工作,因为 jQuery 需要它。
So what you're getting back is correct, but it's not what you need. What you need for JSONP calls would look like this:
所以你得到的东西是正确的,但这不是你需要的。JSONP 调用所需的内容如下所示:
functionName({
"mall": {
"name": "South Shore Plaza",
"city": "Braintree",
"directory": "/assets/directory/0000/0094/show_floorplan.aspx",
"postal_code": "02184",
"street": "250 Granite St",
"lng": -71.023692,
"id": 147,
"phone": "(781) 843-8200",
"lat": 42.218688,
"state": "MA"
}
});
... since what comes back currently is not valid JavaScript (by itself, and that's what it is), and that's how JSONP works, the response actually needs to be executable JavaScript.
...因为当前返回的不是有效的 JavaScript(就其本身而言,就是这样),这就是 JSONP 的工作方式,因此响应实际上需要是可执行的 JavaScript。
You can get the same error by just plopping that code straight in your page in a <script>
block.
您可以通过将该代码直接放入页面中的<script>
块来获得相同的错误。
If you're just after the embedding piece of data, I recommend a plugin like jQuery-oembed, to do that. If you're after the data, you'll need something on your server to process the JSON, then get the data from your server after that.
如果您只是在嵌入数据之后,我推荐一个像jQuery-oembed这样的插件来做到这一点。如果您需要数据,则您的服务器上需要一些东西来处理 JSON,然后从您的服务器获取数据。
For example
例如
so let's say we would like to make a cross-domain using jQuery. Here is how the jQuery $.ajax
call should look like:
所以假设我们想使用 jQuery 进行跨域。下面是 jQuery$.ajax
调用的样子:
$.ajax({
dataType: 'jsonp',
data: 'id=test',
jsonp: 'jsonp_callback',
url: 'http://www.differentdomain.com/get_data.php',
success: function () {
// do something
},
});
Now on the server side (in the get_data.phpfile) we have to get the callback name and send the data in JSON format wrapped in the callback function. Something like this:
现在在服务器端(在get_data.php文件中),我们必须获取回调名称并以 JSON 格式发送数据,该数据包装在回调函数中。像这样的东西:
<?php
$jsonp_callback = $_GET['jsonp_callback'];
$data = array('1','2','3');
echo $jsonp_callback . '('.json_encode($data).');';
?>
JSONP can only be used if and when the server properly embed the response in a JavaScript function call.
只有当服务器正确地将响应嵌入到 JavaScript 函数调用中时,才能使用 JSONP。
回答by itinance
It should work.
它应该工作。
Have you watched the request in firebug or another debug console, what happens and what the response is returned?
Please consider the same-origin-policy, so the script which makes this request, should also be loaded from webapp.armadealo.com. If not, you need a jsonp-request. Look at: http://api.jquery.com/jQuery.ajax/
您是否在萤火虫或其他调试控制台中查看了请求,会发生什么以及返回的响应是什么?
请考虑same-origin-policy,因此发出此请求的脚本也应从 webapp.armadealo.com 加载。如果没有,您需要一个 jsonp-request。看:http: //api.jquery.com/jQuery.ajax/