2015-10-22 50 views
0

我希望在“返回false”行后停止执行javascript代码,但它不会。

我的英语很差。如果有人了解我,请提高我的问题谢谢!

$('#category-list input').blur(function(){ 
     var $$ = $(this), $p = $$.prev(); 
     if ($$.val() != $p.html()) { 
      var data = {'key':$$.attr('name'),'value':$$.val()}; 
      $.post('<?php echo Url::to(['field']); ?>', data).done(function(result){ 
       if (result != 'ok'){ 
        alert(result); 
        return false; /*i need it stop at here!!!!!! but it not*/ 
       } 
      }); 
      alert(3); 
      $p.html($$.val()); 
     } 
     $$.hide(); 
     $p.show(); 
    }); 
+0

你要警惕(3)你从服务器的响应后得到执行?你希望$$。hide()在你从服务器得到响应后得到执行吗?等等。请你让我们知道哪些代码应该执行或不应执行 – Don

+1

$ .post()在它自己的时间内异步执行,而不会阻塞周围的代码。该代码根本就不在它被写在订单执行完全的'警报(3);'总是将'.done之前执行(功能(结果){...})'调用回调函数。这类行为的一个很好的解释可以在“[如何返回从异步调用的响应?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-找到异步调用)“ –

+0

在另一个函数中声明一个函数完全不会影响外部函数。考虑:'function outer(){function inner(){return 42; };返回21; }'。你认为'outer()'会返回什么? –

回答

2

简短的回答是因为本身的功能后很可能会着火执行完毕你不能阻止一个Ajax完成函数内部父功能。无论如何,它的2个独立的事件

$.post是一个异步Ajax请求。这意味着该函数的.done()部分将在ajax请求返回后执行。

然而,函数的其余部分同步运行,这意味着每一个代码(或一些)线.post后,将运行服务器甚至响应之前。为了解决这个问题,你需要重新设计你如何执行你的功能。

让我们来看看这一个基本的功能:

function getSomeAjax() { 
    //1 - the alert will execute first 
    alert('first line of execution'); 
    //2 - the post request will execute second 
    $.post('someUrl', data).done(function(result){ 
    if (result != 'ok'){ 
     alert('post request complete'); 
     //this will execute randomly whenever the server responds. 
     //it could be in 1 second, 5 seconds, or 20 seconds 
    } 
    }); 
    //3 
    alert('last line of execution'); 
} 

看着上面的例子,你应该将是依赖于服务器的响应到if语句的任何逻辑。否则,它会不管你的POST请求的执行