您可以在 jquery 中的另一个 AJAX 调用中进行 AJAX 调用吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1264545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:02:50  来源:igfitidea点击:

Can you make an AJAX call inside of another AJAX call in jquery?

jqueryajax

提问by JasonDavis

Below is a jquery script I am working on, I have stripped down all the non-relevant parts of it.

下面是我正在处理的 jquery 脚本,我已经剥离了它的所有不相关部分。

You can see there is an ajax call, from the results there is an if statement, the other items our stripped out but anyways the captcha one is picked from the result of the first ajax call.

您可以看到有一个 ajax 调用,从结果中有一个 if 语句,我们删除了其他项目,但无论如何验证码是从第一个 ajax 调用的结果中挑选出来的。

I then need to make a second ajax call, this is where my trouble is, I get no errors but it doesn't seem to return a response on the second one, am I missing something?

然后我需要进行第二次 ajax 调用,这就是我的问题所在,我没有收到任何错误,但它似乎没有在第二次返回响应,我错过了什么吗?

<script type="text/javascript">
    $(document).ready(function() {
        // make ajax call
        var dataString = 'comment=' + comment;
        $.ajax({
            type: "POST",
            url: "process.php",
            data: dataString,
            dataType: "json",
            success: function(data) {
                //result from 1st ajax call returns "captcha"
                if (data.response === 'captcha') {
                    //a bunch of code is ran
                    ////////////////////////
                    //then...
                    $().bind('cbox_closed', function() {
                        var dataString2 = 'comment=' + comment + '&run=captchagood';

                        // our nested ajax call
                        // this is the part that is having trouble =(
                        $.ajax({
                            type: "POST",
                            url: "process.php",
                            data2: dataString2,
                            dataType: "json",
                            success: function(data2) {
                                if (data2.response === 'captchagood') {
                                    alert('test');
                                    $('div#loader').find('img.load-gif').remove();
                                    $('div#loader').append('<span class="success">Thanks for your comment!</span>');
                                    $('div#loader').hide().fadeIn('slow');
                                    $('span.limit').remove();
                                    $('div#comments').append(data);
                                    $('div#comments div.comment-unapproved:nth-child(1)').hide().slideDown('slow');
                                    $('input#submit-comment').unbind('click').click(function() {
                                        return false;
                                    });
                                    // success append the sanitized-comment to the page
                                    $('#comments').prepend(data.comment);
                                };
                                // end captcha status returned
                            }
                        });
                    });
                };
                return false;
            });
        });
    });
</script>

回答by jammus

There's nothing wrong with having an ajax call inside an ajax callback. In fact, you're not even doing that, what you're doing here is:

在 ajax 回调中进行 ajax 调用并没有错。事实上,你甚至没有这样做,你在这里做的是:

  1. Ajax call
  2. If call is successful and returns 'captcha' then bind a function to the cbox_closed event
  3. When the cbox_closed event is triggered call the bound function which contains another ajax call
  1. Ajax 调用
  2. 如果调用成功并返回“验证码”,则将函数绑定到 cbox_closed 事件
  3. 当 cbox_closed 事件被触发时,调用包含另一个 ajax 调用的绑定函数

Some things to check for:
Is the sever returning successfully? (no 404, 500 error etc)
You're anticipating a json response. Does it contain data like {response:'captcha} that you're checking for?
When is the cbox_closed event triggered? Are you sure that it is happening?

需要检查的一些事项:
服务器是否成功返回?(没有 404、500 错误等)
您期待 json 响应。它是否包含您正在检查的 {response:'captcha} 之类的数据?
cbox_closed 事件何时触发?你确定它正在发生吗?

回答by vdboor

You've passed the 'success' callback to jQuery, but no 'error' callback. This way you're ignoring the error. Here is an example to capture the error, and optionally display it in the Firebug console.

您已将“成功”回调传递给 jQuery,但没有“错误”回调。这样你就忽略了错误。下面是一个捕获错误的示例,并可选择将其显示在 Firebug 控制台中。

var lastRequest = jQuery.ajax( { type:     "POST"
                               , url:      this._ajaxUrl
                               , data:     postdata
                               , dataType: "json"
                               , success:  _gotAjaxResponse
                               , error:    _gotAjaxError
                               } );

function _gotAjaxResponse( data )
{
  window.console && console.log( data );
}

function _gotAjaxError(xhr, status, error)
{
  // Show server script errors in the console.
  if( xhr.status == 500 )
  {
    var response = xhr.responseText;
    response = response.replace( /\r?\n/g, "" )
                       .replace( /(<\/)/g, "\n" )
                       .replace( /<[^>]+>/g, "" )
                       .replace( /^\s+/, "" )
                       .replace( /\s+$/, "" );
    window.console && console.error(response);
  }

  alert("I'm sorry...\n\n"
      + "Unfortunately an error occured while communicating with the server.\n"
      + "Please try again later.");
}