Le_Morri
Le_Morri

Reputation: 1629

jQuery Ajax fails; File is loaded correctly

i'm having trouble using jQuery (v1.9.1) ajax.

Here is the really simple js (common.js):

var BASE_URL = window.location.protocol + '//' + window.location.host + '/';

$(document).ready(function(){
    //load menu
    $.ajax({
        type : 'GET',
        url : BASE_URL + 'menu.json',
        dataType: 'json'
    })
    .done(function(){alert('D');})
    .fail(function(){alert('F');})
    .always(function(){alert('A');});
});

According to Firebug the file (menu.json) is loaded correctly. but the problem ist that i always get the alert-messages F and A.

So why is this really simple code not working? I just can't figure it out.

If needed here is the correspoding html part:

<!DOCTYPE html>
<html>
    <head>
        ...
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/common.js"></script>
    </head>
....

both javascript files are loaded correctly.

UPDATE

Here is the content of menu.json (yep it's static)

[
    {
        "name": "Home",
        "url": "#main"
},
{
        "name": "WTF",
        "url": "#wtf"
    }
]

Upvotes: 0

Views: 92

Answers (1)

Alnitak
Alnitak

Reputation: 339816

Just because the transfer succeeded doesn't mean that the AJAX call did. Most likely your response is not valid JSON. You may also need to ensure that the web server returns the correct Content-type for JSON, i.e. application/json.

EDIT confirmed - JSON requires that the keys (and string values) be enclosed in double quotes

The other common reason is Cross-Origin Resource Sharing security issues, although that shouldn't be a factor here since you're downloading from the same site as the current page.

Also, there's really no need to specify BASE_URL - just use the path /menu.json

Upvotes: 3

Related Questions