响应Ajax请求jsonp后继续进程

时间:2012-06-11 09:29:13

标签: jquery ajax json jsonp

var getPageInhalt : function (id){
    var restmethod = "http://localhost:1212/getPageById/"+id+"/jsonp.aspx?callback=?";

    $.ajax({
        url: restmethod,
        type: "GET",
        contentType: "application/json",
        async: false,                        
        dataType: 'jsonp',
        cache: false,
        error: function(){
            return false;
        },
        success: function(data){ 
            console.log(data); --> balblal
            return data;
        }
    });
}

console.log(getPageInhalt(2));-->undefined ?????

1 个答案:

答案 0 :(得分:2)

虽然我不同意同步AJAX(技术上它是矛盾的...... ),你必须从getPageInhalt函数返回值,而不是从ajax回调中返回..

var getPageInhalt = function (id){
    var restmethod = "http://localhost:1212/getPageById/"+id+"/jsonp.aspx?callback=?",
        resultValue;

    $.ajax({
        url: restmethod,
        type: "GET",
        contentType: "application/json",
        async: false,                        
        dataType: 'jsonp',
        cache: false,
        error: function(){
            resultValue = false;
        },
        success: function(data){ 
            console.log(data); //--> balblal
            resultValue = data;
        }
    });

    return resultValue;
}

以下是演示 http://jsfiddle.net/gaby/qHY7g/