Javascript 尝试使用jQuery获取JSON
我试图从中获取带有该示例的JSON 我只是将de-url-JSON编辑为 我将它复制到我的desktop index.html中,但它在本地计算机中不起作用。我试着把它上传到我的网站上,但它不起作用。。。你能帮我吗Javascript 尝试使用jQuery获取JSON,javascript,jquery,html,json,Javascript,Jquery,Html,Json,我试图从中获取带有该示例的JSON 我只是将de-url-JSON编辑为 我将它复制到我的desktop index.html中,但它在本地计算机中不起作用。我试着把它上传到我的网站上,但它不起作用。。。你能帮我吗 <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></scri
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://www.w3schools.com/jquery/demo_ajax_json.js",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
请参阅浏览器控制台:
XMLHttpRequest cannot load http://www.w3schools.com/jquery/demo_ajax_json.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
您不能直接请求该文件,您是不允许的
一种解决方案是使用php,并使用ajax从js调用php文件,您正试图发送跨源请求 安装并签入控制台,您将看到此错误消息 已阻止跨源请求:同一源策略不允许读取位于的远程资源。这可以通过将资源移动到同一域或启用CORS来解决
在这个答案中阅读更多内容我已经在JSFIDLE上上传了运行的代码。请看下面的图片 . 直接转到可能重复的
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://www.google.com/calendar/feeds/developer-calendar@google.com/public/full?alt=json",function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>