Return value of JQuery ajax call(JQuery ajax调用的返回值)
问题描述
我希望这个函数返回 ajax 调用是否成功.有什么办法可以做到这一点吗?我下面的代码没有这样做.
I want this function to return wether or not the ajax call was succesful or not. Is there any way I can do this? My code below doesn't do this.
function myFunction(data) {
var result = false;
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
url: "url",
data: data,
error: function(data){
result = false;
return false;
},
success: function(data){
result = true;
return true;
}
});
return result;
}
推荐答案
很遗憾,您无法将值返回给包装异步回调的函数.相反,来自 AJAX 请求的成功回调会将数据和控制权移交给另一个函数.我在下面演示了这个概念:
Unfortunately, you cannot return values to functions that wrap asynchronous callbacks. Instead, your success callback from the AJAX request will handoff the data and control to another function. I've demonstrated this concept below:
myFunction 的定义:
// I added a second parameter called "callback", which takes a function
// as a first class object
function myFunction(data, callback) {
var result = false;
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
url: "url",
data: data,
error: function(data){
result = false;
// invoke the callback function here
if(callback != null) {
callback(result);
}
// this would return to the error handler, which does nothing
//return false;
},
success: function(data){
result = true;
// invoke your callback function here
if(callback != null) {
callback(result);
}
// this would actually return to the success handler, which does
// nothing as it doesn't assign the value to anything
// return true;
}
});
// return result; // result would be false here still
}
回调函数定义:
// this is the definition for the function that takes the data from your
// AJAX success handler
function processData(result) {
// do stuff with the result here
}
调用你的 myFunction:
var data = { key: "value" }; /* some object you're passing in */
// pass in both the data as well as the processData function object
// in JavaScript, functions can be passed into parameters as arguments!
myFunction(data, processData);
这篇关于JQuery ajax调用的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JQuery ajax调用的返回值
基础教程推荐
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01