我想使用ajax請求獲取我的JSON文件,並且不加載,我想要的是顯示json文件中包含的某些特定數據通過使用一些將包含解析數據的變量並將其輸出顯示在瀏覽器的網頁上。但是當我運行它時,只顯示了我創建的html元素,而在調試器中我發現點擊函數後的代碼沒有執行全部代碼。我使用的代碼如下:我需要解析一個JSON文件並在本地網頁上顯示其數據
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Reading Json Data from Json File</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="scripts/jquery.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() {
debugger;
//start ajax request
$.ajax({
url: "data.json",
//force to handle it as text
dataType: "text",
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('Plugin name: ' + json.name + '<br />Author: ' + json.author.name);
}
});
});
});
</script>
<style>
.button{
margin:20px;
font-size:16px;
font-weight: bold;
padding:5px 10px;
}
</style>
</head>
<body>
<a href="Json file/data.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>
Besides My JSON file named"Data" contains:
{
"name": "select2",
"title": "Select2",
"description": "Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.",
"keywords": [
"select",
"autocomplete",
"typeahead",
"dropdown",
"multiselect",
"tag",
"tagging"
],
"version": "3.4.2",
"author": {
"name": "Igor Vaynberg",
"url": "https://github.com/ivaynberg"
},
"licenses": [
{
"type": "Apache",
"url": "http://www.apache.org/licenses/LICENSE-2.0"
},
{
"type": "GPL v2",
"url": "http://www.gnu.org/licenses/gpl-2.0.html"
}
],
"bugs": "https://github.com/ivaynberg/select2/issues",
"homepage": "http://ivaynberg.github.com/select2",
"docs": "http://ivaynberg.github.com/select2/",
"download": "https://github.com/ivaynberg/select2/tags",
"dependencies": {
"jquery": ">=1.7.1"
}
}
並且我已經將該文件加載到項目資源管理器中的文件夾中。
代碼中刪除解析 – madalinivascu
你打印'的console.log(數據)'? –
它顯示錯誤404:找不到資源文件,無法找到我的json文件 –