0

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"
    }
]
4

1 回答 1

3

仅仅因为传输成功并不意味着 AJAX 调用成功了。您的响应很可能不是有效的 JSON。您可能还需要确保 Web 服务器返回正确Content-type的 JSON,即application/json.

编辑确认 - JSON 要求将键(和字符串值)括在双引号中

另一个常见的原因是跨域资源共享安全问题,尽管这不应该是一个因素,因为您是从与当前页面相同的站点下载的。

此外,实际上不需要指定BASE_URL- 只需使用路径/menu.json

于 2013-06-04T15:25:15.170 回答