我在目录中有一个名为“json.json”的json文件。我想从该文件中获取项目并将其显示在我现在硬编码的UL中。当我尝试获取该文件时,它无法正常工作。任何人都可以帮我退休并将这些项目添加到json文件中。提前致谢
<!doctype html>
<html lang="en">
<head>
<title>Example</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script type = "text/javascript" src = "js/jquery.js"></script>
<script type = "text/javascript" src = "js/jquery_ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</head>
<body>
<table id="myTable" class= "table table-bordered">
<tr>
<th class="col-md-6 text-center success">
List 1
</th>
<th class="col-md-6 text-center danger">
List 2
</th>
</tr>
<tr>
<td class="col-md-6">
<ul id="firstlist">
<li>Apple <img id="Apple" src = "next.jpg" class = "list1"></li>
<li>Orange <img id="Orange" src = "next.jpg" class = "list1"></li>
<li>Avacado <img id="Avacado"src = "next.jpg" class = "list1"></li>
<li>Banana <img id="Banana" src = "next.jpg" class = "list1"></li>
<li>Mango <img id="Mango" src = "next.jpg" class = "list1"></li>
<ul>
</td>
<td class="col-md-6">
<ul class = "seclist" id = "seclist"></ul>
</td>
</tr>
</table>
<script>
$(function(){
$.getJSON('json.json',function(data){
console.log('success');
}).error(function(){
console.log('error');
});
});
</script>
</body>
</html>
我创建了这样的json文件:
{"Fruits":[
{"textToBeDisplayed":"Apple"},
{"textToBeDisplayed":"Orange"},
{"textToBeDisplayed":"Avacado"},
{"textToBeDisplayed":"Banana"},
{"textToBeDisplayed":"Mango"},
]}
答案 0 :(得分:3)
你应该定义这个
<script src="json.json"></script>
答案 1 :(得分:2)
文件名应该用引号作为字符串:
$.getJSON('json.json', function(data){
console.log('success');
}).error(function(){
console.log('error');
});
另请注意,您无法向本地文件系统发出AJAX请求 - 它将被浏览器的安全性阻止。您需要向Web服务器发出请求,无论是本地(WAMP / LAMP / IIS等)还是远程。
答案 2 :(得分:1)
这是方式
$.getJSON('json.json', function(data){
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
答案 3 :(得分:1)
您需要将json数组赋值给变量。 LittleDragon的建议是正确的,但你需要像这样使用它:
var fruits = {"Fruits":[
{"textToBeDisplayed":"Apple"},
{"textToBeDisplayed":"Orange"},
{"textToBeDisplayed":"Avacado"},
{"textToBeDisplayed":"Banana"},
{"textToBeDisplayed":"Mango"},
]};
然后只需在页面上添加<script src="json.json"></script>
,然后就可以从javascript访问fruits json数组。
这里有一个小提琴:http://jsfiddle.net/ar37G/