如何在jsfiddle中添加本地json文件? [英] How to add local json file in jsfiddle?

查看:376
本文介绍了如何在jsfiddle中添加本地json文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在jsfiddle中添加JSON文件?我有一个JSON文件,但我无法在jsfiddle中附加它。我可以创建一个JSON对象并使用它,但有没有办法将外部JSON文件添加到小提琴?

How can I add a JSON file in jsfiddle? I have a JSON file but I am not able to attach it in jsfiddle. I can make a JSON object and use it, but is there any way to add an external JSON file to a fiddle?

推荐答案

您可以利用跨源资源共享(CORS)的强大功能来完成任务。

You can harness the power of Cross-Origin Resource Sharing (CORS) to achieve your task.

基本上CORS的工作原理是如果在HTTP响应中设置 Access-Control-Allow-Orign 标头,那么内容由AJAX加载可以在我们的脚本中使用,无论它是在同一个域还是其他域。

Basically how CORS works is that if the Access-Control-Allow-Orign header is set in the HTTP response, then the content loaded by AJAX can be used in our script regardless of the fact it is on the same domain or some other.

现在为了您的目的,您可以上传本地JSON文件到Dropbox的 Public 文件夹并获取一个公共URL,您可以通过简单的AJAX调用加载。

Now for your purpose, you can upload your local JSON file to Dropbox's Public folder and get a Public URL, that you can load by a simple AJAX call.

AJAX在这种情况下,调用将成功,因为Dropbox在响应 Access-Control-Allow-Orign:* 中设置以下值,这意味着任何域都可以使用加载的内容。

The AJAX call will succeed in this case because Dropbox sets the following value in the response Access-Control-Allow-Orign:* which means any domain can use the loaded content.

Jquery代码将类似于thi s(如果你愿意,你甚至可以使用纯JavaScript)。

Jquery code will be something like this(you can even use pure JavaScript if you prefer ).

var url = 'https://dl.dropboxusercontent.com/u/94145612/example.json';
var myJsonData= {};
$.ajax({
    type: 'GET',
    url: url,
    async: false,
    contentType: "application/json",
    dataType: 'json',
    success: function (data) {
        alert('success');
        console.log(data);
        myJsonData= data;
    },
    error: function (e) {
        alert('error');
        console.log(e);

    }
});

这篇关于如何在jsfiddle中添加本地json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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