JimBo
JimBo

Reputation: 137

How can use $.each for this json

I get a error when want use $.each value json in jquery, in the following are my js code and output json_encode and error. what do i do?

This all output from 'url'(json_encode): http://pastebin.com/gEr0Aa3s

This is my ajax call that give me error:

$.ajax({
            type: "POST",
            dataType: "json",
            url: 'url',
            data: dataString,
            cache: false,
            success: function (data) {
                $.each(data.guide, function (index, value) {
                    $('#guide_name').append('<div>'+ value.guide +'</div>');
                });
                $.each(data.residence, function (index, value) {
                    $('#residence_name').append('<div id="'+value.hotel_id+'">'+ value.name_re +'</div>');
                });
                $.each(data.reunits, function (index, value) {
                    $('#residence_name .li_show').append('<li>'+value.name+'</li>');
                });
            },
            "error": function (x, y, z) {
                alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
            }
        })

Error:

An error has occured:<br>
[object Object]<br>
error<br>
Not Found<br>

Upvotes: 0

Views: 830

Answers (3)

xdazz
xdazz

Reputation: 160833

Besides your json format, you should fix below:

url: 'url'-> If the url is varialbe, remove the quotes.

The z in your error callback function is the textual portion of the HTTP status, and you received Not Found, means your url is not ok.

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150010

The data you posted is not valid JSON.

What you need to work with your code is a structure like this:

{
  "guide" : [ /* your guide array here */ ],
  "residence" : [ /* your residence array here */ ],
  "reunits" : [ /* your reunits array here */ ]
}

Where you should have commas between each of the properties in the object (i.e., what I've put on the end of each line) you've got } {. Also you've repeated "residence" and "reunits" several times, which is something you could achieve with a different structure but wouldn't fit your ajax success code's logic.

Upvotes: 3

Ioannis Karadimas
Ioannis Karadimas

Reputation: 7896

Your JSON is not valid. To see the error for yourself, go to http://jsonlint.com/, and paste your raw code, then hit 'Validate'. I suspect that in line 10, you need to replace }{ with a ,.

EDIT: Actually, looking better at your code, I think you might need to enclose your objects in an array. Keep in mind that JSON is hierarchical, and objects cannot be declared one next to the other, like this: {} {}. Rather, you need to enclose them in a top - level array: [{}, {}].

Upvotes: 2

Related Questions