我有一个foo发出Ajax请求的函数.我怎样才能从中回复foo?
我尝试从success回调中返回值,并将响应分配给函数内部的局部变量并返回该变量,但这些方法都没有实际返回响应.
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result;
}
var result = foo(); // It always ends up being `undefined`.
Run Code Online (Sandbox Code Playgroud) 我这样编码:
$.ajax({ cache: false,
url: "/Admin/Contents/GetData",
data: { accountID: AccountID },
success: function (data) {
$('#CityID').html(data);
},
error: function (ajaxContext) {
alert(ajaxContext.responseText)
}
});
Run Code Online (Sandbox Code Playgroud)
但是当我最后查看jQuery .ajax()文档时,似乎建议我应该像下面这样编码,或者至少它建议添加一个.done()和一个.fail():
var request = $.ajax({ cache: false,
url: "/Admin/Contents/GetData",
data: { accountID: AccountID }
});
request.done(function (data) {
xxx;
});
request.fail(function (jqXHR, textStatus) {
xxx;
});
Run Code Online (Sandbox Code Playgroud)
更新
如果我这样的代码是相同的,还是有一些优势将它分成三个?
$.ajax({ cache: false,
url: "/Admin/Contents/GetData",
data: { accountID: AccountID }
}).done(function (data) {
xxx;
}).fail(function (jqXHR, textStatus) {
xxx;
});
Run Code Online (Sandbox Code Playgroud) 我正在深入研究节点7 async/await功能,并在这样的代码中保持绊脚石
function getQuote() {
let quote = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
return quote;
} …Run Code Online (Sandbox Code Playgroud) 我有一个jquery $ .ajax()函数的小问题.
我有一个表单,每次单击单选按钮或从下拉菜单中选择创建一个具有所选值的会话变量.
现在 - 我有一个下拉菜单有4个选项 - 第一个(标签为None)有一个值=""其他有其ID.
我想要发生的是无选项(带空白值)删除会话而其他选项创建一个,但仅当具有此特定选择名称的会话尚不存在时 - 因为所有其他选项都分配了相同的金额 - 它只是表明选择了哪一个.
我不确定这是否有意义 - 但看看代码 - 也许这会让它更清晰:
$("#add_ons select").change(function() {
// get current price of the addons
var order_price_addon = $(".order_price_addon").text();
// get price of the clicked radio button from the rel attribute
var add = $(this).children('option').attr('label');
var name = $(this).attr('name');
var val = $(this).val();
if(val == "") {
var price = parseInt(order_price_addon) - parseInt(add);
removeSession(name);
} else {
if(isSession(name) == 0) {
var price = parseInt(order_price_addon) + …Run Code Online (Sandbox Code Playgroud) 我想要一个从ajax请求返回值的函数.我想停止javascript执行,直到函数获取其值由ajax异步请求返回.就像是:
function myFunction() {
var data;
$.ajax({
url: 'url',
data: 'data to send',
success: function (resp) {
data = resp;
},
error: function () {}
}); // ajax asynchronus request
return data; // return data from the ajax request
}
Run Code Online (Sandbox Code Playgroud) 我想创建一个JavaScript函数,它返回jQuery AJAX调用的值.我想要这样的东西.
function checkUserIdExists(userid){
return $.ajax({
url: 'theurl',
type: 'GET',
cache: false,
data: {
userid: userid
},
success: function(data){
return data;
}
});
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过将async设置为false来做到这一点,但我宁愿不这样做.
如何在nodejs中使用ES7(ECMAScript 2016)?我怎样才能在生产中使用它?
在哪个版本的节点中,我不需要使用任何模块来做到这一点?
任何帮助表示赞赏.
我刚安装了Node v7.2.0并了解到以下代码:
var prm = Promise.reject(new Error('fail'));
Run Code Online (Sandbox Code Playgroud)
结果如下:
(node:4786) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: fail
(node:4786) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Run Code Online (Sandbox Code Playgroud)
我理解这背后的原因,因为许多程序员可能已经经历了Error最终被一个人吞没的挫败感Promise.然而,我做了这个实验:
var prm = Promise.reject(new Error('fail'));
setTimeout(() => {
prm.catch((err) => {
console.log(err.message);
})
},
0)
Run Code Online (Sandbox Code Playgroud)
这导致:
(node:4860) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: fail
(node:4860) DeprecationWarning: Unhandled promise rejections …Run Code Online (Sandbox Code Playgroud) 我正在创建一个ajax实用程序,用于连接我的服务器方法.我想从jQuery.ajax()调用返回的对象中利用jQuery 1.5+延迟方法.情况如下.
serverside方法始终返回JSON对象:
{ success: true|false, data: ... }
客户端实用程序启动这样的ajax调用
var jqxhr = $.ajax({ ... });
问题领域:
jqxhr.success(function(data, textStatus, xhr) {
if(!data || !data.success) {
???? // abort processing, trigger error
}
});
return jqxhr; // return to caller so he can attach his own handlers
Run Code Online (Sandbox Code Playgroud)所以问题是如何取消所有调用者的调用附加成功回调触发他的错误处理程序在提到的地方?????
文档说延迟函数调用列表是FIFO,所以我的成功处理程序绝对是第一个.
节点程序员通常使用这样的范例:
var callback = function(err, data) {
if (err) { /* do something if there was an error */ }
/* other logic here */
};
Run Code Online (Sandbox Code Playgroud)
为什么不简化函数只接受一个参数,即错误或响应?
var callback = function(data) {
if (isError(data)) { /* do something if there was an error */ }
/* other logic here */
};
Run Code Online (Sandbox Code Playgroud)
似乎更简单.我能看到的唯一缺点是函数不能将错误作为实际预期的返回值返回 - 但我相信这是一个非常微不足道的用例.
为什么错误优先模式被认为是标准的?
编辑:执行isError:
var isError = function(obj) {
try { return obj instanceof Error; } catch(e) {}
return false;
};
Run Code Online (Sandbox Code Playgroud)
另一种编辑:我的备用方法是否有可能比节点约定更方便,因为只接受一个参数的回调更可能是非回调用例的可重用方法?
jquery ×6
javascript ×4
node.js ×4
ajax ×2
async-await ×1
asynchronous ×1
callback ×1
ecmascript-7 ×1
es6-promise ×1
jquery-1.5 ×1