Return value of $.post() call

后端 未结 2 974
不知归路
不知归路 2021-01-24 07:49

I have a jquery $.post function lik so:

$.post(\'/test\',json_data, function(data) {
                                result=data
});

this fun

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-24 08:08

    This is considered a bad practice but there is an async parameter in $.ajax() that you can set to false and wait synchronously for a result:

    var result;
    $.ajax({
      type: 'POST',
      url: '/test',
      data: json_data,
      async: false,
      success: function(data) {
        result=data;
      },
      dataType: 'application/json'
    });
    //result available here
    

    A more idiomatic, although slightly less convenient in this case, would be to take advantage of callbacks:

    function validate(okCallback, errorCallback) {
        $.post('/test',json_data, function(data) {
            if(data) {
                okCallback();
            } else {
              errorCallback();
            }
        });
    }
    
    validate(
        function() {
            //proceed
        },
        function() {
            //display validation error
        }
    }
    

提交回复
热议问题