Data from post request

有些话、适合烂在心里 提交于 2019-12-02 14:09:50

问题


var pload = function(ctrl, func){
    var dataa;
    $.post("/index.php/"+ctrl+"/"+func,{}, function(data){
    dataa = data;
    });
    return dataa;
};

var bind = function(hashtag, ctrl, func, div){
    $(document).on("click", "a[href="+hashtag+"]", function() {
            var body = pload(ctrl, func);
             alert(body);
            $(div).html(body);
    })
}

How I can get data in global? I want, so pload return data from post request. But I get "undefined" in alert()


回答1:


Try using callback.

function pload(ctrl, func,callback){
    $.post("/index.php/"+ctrl+"/"+func,{}, function(data){
        callback(data);
    });
};

var bind = function(hashtag, ctrl, func, div){
    $(document).on("click", "a[href="+hashtag+"]", function() {
        pload(ctrl, func,function(body){
            alert(body);
            $(div).html(body);
        });             
    })
}



回答2:


tyr this:

var pload = function(ctrl, func){
    var dataa;
    $.post("/index.php/"+ctrl+"/"+func,{}, function(data){
    dataa = data;
    return dataa;
    });

};



回答3:


You're not getting any value back because $.post is asynchronous, and won't halt the program until it receives a value back.

You should move the data handling portion to the function which will be called when the async call returns its result.

var pload = function(ctrl, func){
    var dataa;
    $.post("/index.php/"+ctrl+"/"+func,
      {}, 
      //this function will be called when $.post receives its response
      function(data){
        alert(data);
        $(div).html(data);
      });
    return dataa;
};


来源:https://stackoverflow.com/questions/21018766/data-from-post-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!