开发者

Using JSON with Jquery Ajax

I started my hands on training on Jquery AJAX JSON this morning. I have knowledge of Jquery but JSON & Ajax is something new to me.

I have developed a small snippet of code to read JSON file with ajax and show the data values by appending the list.

using following div in body section.

<div id="tabPanelWrapper"></div>

Javascript:

$(document).read开发者_开发百科y(function() {

    // Calling Ajax Function
    loadContent();                          

});

function loadContent() {
    $.ajax({
       type: "GET",
       url: "data.js",
       dataType: "json",
       cache: false,
       contentType: "application/json",
       success: function(data) {
        alert("Success");
        $.each(data.dashboard, function(i,post){
            $('#tabPanelWrapper').append('<ul><li>' + data.id + '</li><li>' + data.name +'</li></ul>');
        });
      },
        error: function(xhr, status, error) {
            alert(xhr.status);
        }
    });
}

JSON File:

{
    dashboard: [
    {
        "id": "tcm:20-1869",
        "name": "FEATURED ARTICLE"
    },
    {
        "id": "tcm:20-1869",
        "name": "FEATURED ARTICLE"
    }
]
}

Page is throwing 404 error. Please help me with this code.

Thanks in advance | Lokesh Yadav


a 404 error is a Page Not found error. I'd try to browse to the data.js file you're trying to access, and maybe try to write out the full url to the file in your .ajax-call.

I.e.

 http://myhost.com/script/data.js

if that's the location of your script.

UPDATE Your error is invalid Json. If you check the error argument in your Error-function, you'd see that.

Try adding quotes around dashboard, and you should be one step further!

And you'll also have to change in your success-method:

 $.each(data.dashboard, function(i,post){
            $('#tabPanelWrapper').append('<ul><li>' + post.id + '</li><li>' + post.name +'</li></ul>');
        });

note that I'm looking at post.id and post.name since that is the current item in the $.each enumeration. data.id would look for an id-property next to dashboard in your Json, but that doesn't exist.


change

$.each(data.dashboard, function(i,post){
        $('#tabPanelWrapper').append('<ul><li>' + data.id + '</li><li>' + data.name +'</li></ul>');
});

to

 $.each(data.dashboard, function(i,post){
        $('#tabPanelWrapper').append('<ul><li>' + post.id + '</li><li>' + post.name +'</li></ul>');
 });

defnitely the 404 error is not due to this.


Check the URL property. An 404 error is not a json error.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜