我正在尝试使用 JQuery 解析此外部 JSON 文件:
var items={ "menu" : [
{"id": "TN", "value": "ar"} ,
{"id": "FR", "value": "fr"} ,
{"id": "GB", "value": "en"} ,
{"id": "US", "value": "en"}
]
}
对于这个 HTML 文件,我想知道语法是否有错误:
<!DOCTYPE html>
<html>
<head>
<title>Your New Application</title>
<style type="text/css">
/* Prevent copy paste for all elements except text fields */
* { -webkit-user-select:none; -webkit-tap-highlight-color:rgba(255, 255, 255, 0); }
input, textarea { -webkit-user-select:text; }
body { background-color:white; color:black }
</style>
<script type="text/javascript">
/* This code is used to run as soon as Intel activates */
var onDeviceReady=function(){
//hide splash screen
intel.xdk.device.hideSplashScreen();
};
document.addEventListener("intel.xdk.device.ready",onDeviceReady,false);
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
//When DOM loaded we attach click event to button
$(document).ready(function() {
//after button is clicked we download the data
$('.button').click(function(){
//start ajax request
$.ajax({
url: "pays.json",
//force to handle it as text
dataType: "json",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//now json variable contains data in json format
//let's display a few items
$('#results').html('Country: ' + json.items.menu[0].id + '<br />Language: ' + json.items.menu[0].value);
}
});
});
});
});
</script>
</head>
<body>
<a href="pays.json" target="_blank">Open JSON file</a><br />
<input type="button" value="Get and parse JSON" class="button" />
<br />
<span id="results"></span>
</body>
</html>
问题是我没有得到任何输出。 有什么错误吗?预先感谢!
最佳答案
如果第一部分应该是“外部 JSON”文件的内容,那么它就不是 JSON。这只是在文件中声明对象的 JavaScript。删除 var items=
部分,使其实际上是有效的 JSON,然后您可以执行以下操作:
$.ajax({
url: "pays.json",
//force to handle it as text
dataType: "json",
success: function (data) {
$('#results').html('Country: ' + data.menu[0].id + '<br />Language: ' + data.menu[0].value);
}
});
我删除了对 $.parseJSON()
的调用,因为不需要它。如果您为 AJAX 请求指定 dataType: 'json'
,响应将自动解析为 JSON,然后结果(如果解析没有失败)将作为第一个参数传递给 成功
函数。这意味着该函数内部的 data
是您的对象。
您的对象中也没有声明 items
属性,只有 menu
,因此我将其从 json.items.menu
更改为只是data.menu
。
关于javascript - 解析外部 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22630138/