返回AJAX调用数据的JavaScript函数
我想创建一个JavaScript函数,它返回jQuery AJAX调用的值。 我想要这样的东西。
function checkUserIdExists(userid){ return $.ajax({ url: 'theurl', type: 'GET', cache: false, data: { userid: userid }, success: function(data){ return data; } }); }
我知道我可以通过将async设置为false来实现此目的但我宁愿不这样做。
使用jQuery 1.5,您可以使用全新的$.Deferred
function,这正是为了这个function。
// Assign handlers immediately after making the request, // and remember the jqxhr object for this request var jqxhr = $.ajax({ url: "example.php" }) .success(function() { alert("success"); }) .error(function() { alert("error"); }) .complete(function() { alert("complete"); }); // perform other work here ... // Set another completion function for the request above jqxhr.complete(function(){ alert("second complete"); });
资源
你不能返回AJAX调用返回的数据,除非你想同步调用它(你不相信我 – 相信我)。 但是你可以返回的是对AJAX调用返回的数据的承诺 ,你可以以非常优雅的方式实现它。
( 更新:请注意,目前jQuery Promises与Promises / A +规范不兼容 – 在这个答案中有更多信息。)
基本上你可以返回$ .ajax(…)调用的返回值:
function checkUserIdExists(userid){ return $.ajax({ url: 'theurl', type: 'GET', cache: false, data: { userid: userid } }); }
并且调用你的函数的人可以像这样使用它:
checkUserIdExists(userid).success(function (data) { // do something with data });
如果您有兴趣,请参阅我的这篇文章以获得更好的解释和演示。
你可以传递一个回调函数:
function checkUserIdExists(userid, callback) { $.ajax({ ... success: callback }); } checkUserIdExists(4, function(data) { });
从jQuery 1.8开始,不推荐使用“成功”,“错误”和“完整”回调。 相反,你应该使用“完成”,“失败”和“永远”。
所以你可以:
function checkUserIdExists(userid, callback) { return $.ajax({ url: 'theurl', type: 'GET', cache: false, data: { userid: userid } }) .done(callback) .fail(function(jqXHR, textStatus, errorThrown) { // Handle error }); } checkUserIdExists(2, function(data) { console.log(data); // Do what you want with the data returned });
这不是JavaScript异步编程真正意图完成的方式。 而是在成功函数中使用回调来调用另一个函数来使用从服务器返回的数据。
蒂姆,这两种情景是相互排斥的; 异步操作不会用于任何目的,也不能检索返回的数据。
您应该查看ajax调用的启用事件的基础结构