如何使用javascript从外部域读取JSON

时间:2016-04-21 17:06:24

标签: json jsonp getjson stringify

我是javascript的新手。 我有一个在本地读取JSON文件的工作代码,现在JSON移动到另一个域,我无法读取它。我看到了关于JSONP的所有问题,但是没有成功使它工作。

原始代码:



<!DOCTYPE html>
<html>
<head>
	  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
	  <link rel="stylesheet" href="./index_files/style.css">
 	  <link rel="stylesheet" type="text/css"   
</head>
<body class="UI">
<h1 id="number"></h1>

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>

$.getJSON('data.json', function(data)
{
 var views=data.mysite.today; 
 document.getElementById("number").innerHTML = formatNumber(views);
});

</script>
</body>
</html>
&#13;
&#13;
&#13;

JSON文件(data.json)如下所示:

&#13;
&#13;
{
     "mysite":
     {
         "today": 1000,
         "week": 7000,
         "month": 30000
     },
	 "another_site":
     {
         "today": 100,
         "week": 700,
         "month": 3000 
     }
     
 }
&#13;
&#13;
&#13;

让我们说data.json位于:http://www.example.com/data.json

试过这个,但显然没有用:

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
	  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
	  <link rel="stylesheet" href="./index_files/style.css">
  	  <link rel="stylesheet" type="text/css"   
</head>
<body class="UI">
<h1 id="number"></h1>

<script  type = "text/javascript">
a = function(data) {
      console.log(JSON.stringify(data));
	   var obj=JSON.parse(data);
	   var views =obj.mysite.today;
 	   document.getElementById("number").innerHTML = formatNumber(views);
    };
</script>
<script type = "text/javascript" src = "http://www.example.com/data.json"></script>
</body>
</html>
&#13;
&#13;
&#13;

提前致谢。

2 个答案:

答案 0 :(得分:1)

使用jQuery,你可以像这样使用JSONP从远程服务器上获取东西..

$.ajax({
    url: "full url to remote page goes here",
    dataType: "jsonp",
    success: function( response ) {
        console.log( response ); // server response
    }
});

答案 1 :(得分:0)

从我的例子中了解到这一点:

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
	  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
	  <link rel="stylesheet" href="./index_files/style.css">
 	  <link rel="stylesheet" type="text/css"   
</head>
<body class="UI">
<h1 id="number"></h1>

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>


$.ajax({
    url: "http://www.example.com/data.json",
    dataType: "jsonp",
    success: function( response ) {
		var views=response.today; 
 		document.getElementById("number").innerHTML = formatNumber(views);
        console.log( response ); // server response
    }
});

</script>
</body>
</html>
&#13;
&#13;
&#13;

屏幕上没有任何内容,控制台上的错误是: 未捕获的SyntaxError:意外的令牌: