如何从JavaScript读取网站上托管的外部JSON文件? [英] How do I read an external JSON file hosted on a site from JavaScript?

查看:108
本文介绍了如何从JavaScript读取网站上托管的外部JSON文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何读取另一台服务器上托管的JSON文件? 有一个托管JSON数据的网站,我想通过JavaScript访问它. JSON数据位于 Open Notify API .

How do I read a JSON file that is hosted on another server? There is a site which hosts JSON data and I want to access it through JavaScript. The JSON data is on the Open Notify API.

其他问题的问题以及我在Internet上发现的东西并没有帮助我,因为它们全都与本地JSON文件有关!

The problem with other questions asked and things I found on the Internet don't help me because they're all about local JSON files!

我也尝试了jQuery,但是没有用.无论如何,当我查看语法时,函数的 script 部分必须是服务器上的PHP脚本.我将JSON文件放在该位置,但是什么也没发生.我使用了$.get()方法.

I also tried jQuery but it didn't work. Anyways, when I looked at the syntax, the script part of the function had to be a PHP script on the server. I put the JSON file in that spot but nothing happened. I used the $.get() method.

如果有人回答我,我将不胜感激.

I would really appreciate it if someone answered me.

谢谢!

推荐答案

以与调用本地JSON文件几乎相同的方式,您可以从另一个URL提取在线JSON文件的内容.

In pretty much the same manner you'd call a local JSON file, you can fetch the contents of an online JSON file from another URL.

话虽如此,您应该记住,URL应该提供跨域标头,以允许您的域请求该资源.

That being said, you should keep in mind that the URL should provide cross-origin headers to allow your domain to request that resource.

您提到的 URL 具有这些标头,您可以使用它.但是,他们的Web服务器不支持HTTPS,因此在这里我不能使用它作为示例,因此我将使用

The URL you mentioned has those headers and you can use it. However, their web server doesn't support HTTPS so I can't use it as an example here, thus I will use this JSON for the sake of the example:

$.getJSON(
  "https://jsonplaceholder.typicode.com/todos/1",
  function( data ) {
     $('div#title span').html(data.title);
     $('div#completed span').html(data.completed?'true':'false');
  }
);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='title'>Title: <span></span></div>
<div id='completed'>Completed: <span></span></div>

这篇关于如何从JavaScript读取网站上托管的外部JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆