一旦浏览器收到200ok,就中止或标记ajax请求

时间:2014-12-24 13:50:42

标签: javascript php jquery

我有以下要求

// =============================================== start()
//
// clicked_button : the user click the start button.
// app_path       : the app path
//
// return none.
//
var start = function(clicked_button, app_path) {

    $.ajax({
        type: 'POST',
        data: { 'app_path': app_path },
        url: '/app/start',
        context: clicked_button,
    })

    .done(function(data) {
        console.log(data);
        $(this).removeClass('btn-success');
        $(this).addClass('btn-danger');
        $(this).text('stop');
    })

    .fail(function(data) {
        console.log('failed to start the app: ' + data);
    })
};

请求被发送到服务器,操作完成,我测试了,浏览器接收200 OK,我检查了,但不知怎的,.done函数中的代码没有被执行,就像请求还没有完成一样。

如何检查浏览器是否收到200 ok,然后中止ajax调用,并继续jquery代码。

3 个答案:

答案 0 :(得分:1)

你不需要这样做。

您可以在ajax中使用success函数。

  $.ajax({
        type: 'POST',
        data: { 'app_path': app_path },
        url: '/app/start',
        context: clicked_button,
        success: function(data){
           console.log(data);
           $(this).removeClass('btn-success');
           $(this).addClass('btn-danger');
           $(this).text('stop');
        },
        error: function(data){
           console.log('failed to start the app: ' + data);
        }
    })

试试这个代码,看看你的firebug是否有任何问题!

答案 1 :(得分:0)

使用dataType:' json'为了获得服务器响应

答案 2 :(得分:0)

我通过将这些行添加到我的php代码来解决这个问题:

sleep(1);
return Redirect::home();

为什么?

在调试代码之后,它看起来像我请求的所有操作都已完成,所以唯一的问题是请求正在等待,或者以某种方式丢失了回来......

我最好的建议是因为我在我的代码上使用proc_open ..

仍然不是最好的解决方案,但它正在发挥作用,我很高兴。