读取json并将内容放入div
我需要像这样读取 json:
{"error_message":"Only post requests are allowed","reservations":null,"error_code":1}
并将结果放入 3 个不同的 div 中。我正在观看这段代码 使用 JSON 显示数据的最佳方式jQuery 更改 json 链接并链接 jquery 的外部资源,但我找不到问题出在哪里。谢谢
这是我的实际代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("./reservations.json",function(data){
$.each(data, function(i,post){
content += '<h3>' + error_message + '</h3>';
$(content).appendTo("#error_message");
});
});
});
</script>
</head>
<body>
<div class="container">
<div id="error_message"></div>
<div id="reservations"></div>
<div id="error_code"></div>
</div>
</body>
</html>
i need to read from json like this:
{"error_message":"Only post requests are allowed","reservations":null,"error_code":1}
and put the results into 3 different div. I'm watching this code Best way to display data via JSON using jQuery changing the json link and linking the external resource of jquery but i can't find where is the problem. thanks
here is my actual code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("./reservations.json",function(data){
$.each(data, function(i,post){
content += '<h3>' + error_message + '</h3>';
$(content).appendTo("#error_message");
});
});
});
</script>
</head>
<body>
<div class="container">
<div id="error_message"></div>
<div id="reservations"></div>
<div id="error_code"></div>
</div>
</body>
</html>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
content
和error_message
都没有在任何地方定义,因此这一行不起作用。尝试使用:
此外,如果 JSON 与问题中显示的完全相同,则不需要
$.each
。Neither
content
norerror_message
is defined anywhere, so this line won't work.Try using:
Also, if the JSON is exactly like shown in the question, you don't need
$.each
.假设您的 JSON 存储在变量中:
假设您的 3 个
div
是如果您想将错误消息放入每个
div
中:Providing your JSON is stored in a variable:
Let's say your 3
div
s areIf you wanted to place the error message into each of those
div
s: