wait for a jquery ajax callback from calling function

后端 未结 4 1646
悲哀的现实
悲哀的现实 2020-11-27 07:01

I have reviewed a lot of answers to this type of question and now I am confused as to the best way. Given the latest jquery, I am wanting to

  1. Call an ajax funct
4条回答
  •  日久生厌
    2020-11-27 07:31

    You've got to use a callback function. Try this below:

    $(function() {
    
       // I think doAjax should doAnAjax()
       // here you're passing callback
       // but you're not using it doAnAjax()
    
        doAnAjax(Url, data, function(myRtn) {
            if (myRtnV == "success") {
                resetForm($('#myForm'));
                resetForm($('form[name=addChlGrp]'));
            } else {
                $('.rtnMsg').html("Opps! Ajax Error");
            }
        });
    });
    
    // pass callback as third parameter to doAnAjax()
    
    function doAnAjax(newUrl, data, callBack) {
        $.ajax({
            url: newUrl,
            async: true,
            dataType: 'html',
            beforeSend: function() {
                $('.rtnMsg').html("");
            },
            type: "GET",
            data: data,
            cache: false,
            success: function(data, textStatus, xhr) {
                $('.rtnMsg').html(data);
                myRtnA = "Success"
                return callBack( myRtnA );  // return callBack() with myRtna
            },
            error: function(xhr, textStatus, errorThrown) {
                $('.rtnMsg').html("opps: " + textStatus + " : " + errorThrown);
                myRtnA = "Error"
                return callBack ( myRtnA ); // return callBack() with myRtna
            }
        });
    

提交回复
热议问题