Return value of $.post() call

后端 未结 2 939
不知归路
不知归路 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:04

    Check for validity inside the callback

     $.post('/test',json_data, function(data) {
        var result=data;
        if(result === true) {
            // do some ok processing...
            } else {
            // do not ok processing...
            }
    });
    
    0 讨论(0)
  • 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
        }
    }
    
    0 讨论(0)
提交回复
热议问题