开发者

read json and put content to div

开发者 https://www.devze.com 2023-02-22 02:55 出处:网络
i need to read from json like this: {\"error_message\":\"Only post requests are allowed\",\"reservations\":null,\"error_code\":1}

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>


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

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

Try using:

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

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");


Providing your JSON is stored in a variable:

var json = {"error_message":"Only post requests are allowed","reservations":null,"error_code":1};

Let's say your 3 divs are

<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>

If you wanted to place the error message into each of those divs:

$('#div1, #div2, #div3').text(json.error_message);
0

精彩评论

暂无评论...
验证码 换一张
取 消