读取json并将内容放入div [英] read json and put content to div

查看:329
本文介绍了读取json并将内容放入div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要这样读取json:

i need to read from json like this:

{"error_message":"Only post requests are allowed","reservations":null,"error_code":1}

并将结果放入3个不同的div中.我正在观看此代码使用JSON通过JSON显示数据的最佳方法jQuery 更改json链接并链接jquery的外部资源,但我找不到问题所在.谢谢

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

这是我的实际代码:

<!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>

推荐答案

content += '<h3>' + error_message + '</h3>';

在任何地方都没有定义contenterror_message,因此该行将不起作用.

Neither content nor error_message is defined anywhere, so this line won't work.

尝试使用:

var content = '<h3>' + post.error_message + '</h3>';

此外,如果JSON与问题中显示的完全一样,则不需要$.each.

Also, if the JSON is exactly like shown in the question, you don't need $.each.

var content = '<h3>' + data.error_message + '</h3>';
$(content).appendTo("#error_message");

这篇关于读取json并将内容放入div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆