2017-06-12 71 views
0

我该如何检测函数中的AJAX调用是成功还是失败?假设我在其他地方称此功能。如何判断函数中的AJAX调用是否返回错误或成功?

file.js

function doSmallThing(param1, param2) { 

$.ajax({ 
    type: 'post', 
    url: 'some_url', 
    dataType: 'json', 
    ... 
    success: function (result) { 

    // doStuff, signal that this code block is reached 

    }, 

    error: function (error) { 
    // signal that this is reached 
    } 

}) 

} 

file2.js

import File from "..location/of/file.js"; 

class SomeComponent extends React.Component { 

    doSomething() { 

    // stuck here 

    if (File.doSmallThing(param1, param2) does not throw an error) { 
     doMoreThings(); 
    } else { 
     // do nothing 
    } 



    } 

} 

如何将检测的结果:

File.doSmallThing(param1, param2) 

请帮助。谢谢。

+0

看看jquery Promise https://api.jquery.com/promise/ –

+0

你可以将一个回调函数传入'doSmallThing',比如'doSmallThing(param1,param2,functionOnSuccess,functionOnFail)',然后调用'functionOnSuccess ()'当Ajax请求成功时失败。这将使控制流回到file2.js中。 –

+0

您可以将doMoreThings设置为ajax函数的成功回调,而不是根据doSmallThing是否成功执行if包装doMoreThings – James

回答

0

既然你做一个Assincronous电话,你不知道的

File.doSmallThing(param1, param2) 
其执行,acctually,Ajax调用甚至还没有被你到达下一行时间结束后

结果。

我会检查你是如何构建你的代码。首先问自己为什么你必须知道是否有错误。所有错误处理都应在内部完成

error: function (error) { 
    // signal that this is reached 
} 

如果一切都失败了,您可以传递一个回调函数和/或设置一个标志。

相关问题