JQuery回调方法不一致

时间:2012-08-02 18:41:37

标签: jquery json

这里我试图从REST API数据请求数据并使用JQuery在网页中显示。

我正在做3个不同的请求,大约需要200毫秒,300毫秒,7000毫秒的响应时间。这里有两个调用方法被调用,我不明白为什么第三个调用方法没有被调用。使用Firebug工具进行调试时,响应来自服务器。

当下面的函数顺序改变时,行为也会发生变化。正在调用一个或两个回调方法中的任何一个。

请帮我解决这个问题。

$.getJSON(
    "http://115.111.168.221:8080/AnalysisWebService/getDataFromSocialMedia?searchString=wellpoint&startDate=2012-08-01&endDate=2012-08-04&method=getAnalysisRange",
    function(json) {

        }

$(function () {
$.getJSON(
"http://115.111.168.221:8080/AnalysisWebService/getDataFromSocialMedia?searchString=wellpoint&source=facebook,twitter&searchFrom=socialmention&method=getTodayAnalysis",        

function(json) {

}
}
);
);

$(function () {
$.getJSON(
"http://115.111.168.221:8080/AnalysisWebService/getDataFromSocialMedia?searchString=wellpoint&source=facebook,twitter&searchFrom=socialmention&method=getCurrentAnalysis",      

function(json) {

}
}
);
);

2 个答案:

答案 0 :(得分:1)

您的语法似乎已关闭,括号和parens未正确排列。如果您查看Firebug,则应该在页面上收到错误。

<强>更新 我相信您的代码应该格式化为:

$.getJSON(
    url,
    function(json) {

    }
)

$(function () {
    $.getJSON(
    url,      

        function(json) {

        }
    )
}
);

$(function () {
    $.getJSON(
        url,      

        function(json) {

        } 
    )
}
);

此外,您应该考虑将重复代码移动到一个函数中,并且只使用一个document.ready调用。这将使您的代码更健壮,更易于阅读。

答案 1 :(得分:1)

试试这个:

var url = 'http://115.111.168.221:8080/AnalysisWebService/getDataFromSocialMedia?searchString=wellpoint';

$.getJSON(url + '&startDate=2012-08-01&endDate=2012-08-04&method=getAnalysisRange', function (json) {
    // do something
});

$.getJSON(url + '&source=facebook,twitter&searchFrom=socialmention&method=getTodayAnalysis', function (json) {
    // do something
});

$.getJSON(url + '&source=facebook,twitter&searchFrom=socialmention&method=getCurrentAnalysis', function (json) {
    // do something
});

您不需要将它们包装在其他任何内容中,因为DOM不必准备好以便您发出一些请求。

更好的是,为了更具可读性,做一些这样的事情:

var url = 'http://115.111.168.221:8080/AnalysisWebService/getDataFromSocialMedia';

$.getJSON(url, {
    searchString: 'wellpoint',
    startDate: '2012-08-01',
    endDate: '2012-08-04',
    method: 'getAnalysisRange'
}).success(function(json) {
    console.log(json);
}).error(function() {
    console.log('error!');
});

$.getJSON(url, {
    searchString: 'wellpoint',
    source: 'facebook,twitter',
    searchFrom: 'socialmention',
    method: 'getTodayAnalysis'
}).success(function(json) {
    console.log(json);
}).error(function() {
    console.log('error!');
});

$.getJSON(url, {
    searchString: 'wellpoint',
    source: 'facebook,twitter',
    searchFrom: 'socialmention',
    method: 'getCurrentAnalysis'

}).success(function(json) {
    console.log(json);
}).error(function() {
    console.log('error!');
});

编辑:我也附加了错误处理程序,并删除了?来自网址。