在Javascript中将函数赋值
你好, 我尝试将Ajax请求的结果分配给变量。我尝试了下面两个请求,没有结果(得到了一个“未定义”的答案)。 我不理解以下两者之间的区别:在Javascript中将函数赋值,javascript,ajax,Javascript,Ajax,你好, 我尝试将Ajax请求的结果分配给变量。我尝试了下面两个请求,没有结果(得到了一个“未定义”的答案)。 我不理解以下两者之间的区别: var temp = obj.method(me, you); 及 以下是AJAX请求: ObjID.prototype.getAjx = function(one, you){ $.ajax({ type: "post", url: "./php/getAJX.php", dataType: 'jso
var temp = obj.method(me, you);
及
以下是AJAX请求:
ObjID.prototype.getAjx = function(one, you){
$.ajax({
type: "post",
url: "./php/getAJX.php",
dataType: 'json',
context: this,
data: { one: one, two: two },
success: function(data) {
this.myProperty = data[0][0];
},
error:function(request, status, error) {
console.log("Something went wrong." + request.responseText + status + error);
}
});
}
这是一样的吗?
谢谢你的帮助!:) 您显示的前两位代码有效地完成了相同的任务 然而,他们都没有做你认为他们做的事。它们都没有在任何地方分配AJAX调用的返回值: 代码的第一行:
ObjID.prototype.getAjx = function(one, you){
只需将包含实际AJAX调用的函数分配给ObjID.prototype
的.getAjx
属性。该函数不包含任何return
语句,执行时不会返回任何内容。这就是您得到未定义的的原因
实际执行AJAX调用的代码是:
$.ajax({
type: "post",
url: "./php/getAJX.php",
dataType: 'json',
context: this,
data: { one: one, two: two },
success: function(data) {
this.myProperty = data[0][0];
},
error:function(request, status, error) {
console.log("Something went wrong." + request.responseText + status + error);
}
});
而且,您没有将该返回值赋给任何对象。如果你想写的话,你需要这样写:
var result = $.ajax({
type: "post",
url: "./php/getAJX.php",
dataType: 'json',
context: this,
data: { one: one, two: two },
success: function(data) {
this.myProperty = data[0][0];
},
error:function(request, status, error) {
console.log("Something went wrong." + request.responseText + status + error);
}
});
jqueryajax调用,这就是您在这种情况下要存储的内容。这不可能是您的全部代码。AJAX请求在哪里?请发布完整的相关代码。@ScottMarcus如果这是一个最低可行且完整的示例,我可以不看代码墙。@stealththeninja这既不可行也不完整的示例。@stealththeninja对您来说太好了。但是,由于提供的代码没有显示任何AJAX调用,您将有点难以解决这个问题。我没有要求所有的代码,只是相关的。好吧,谢谢斯科特!这很有帮助。很明显,你理解了我的需要:)
var result = $.ajax({
type: "post",
url: "./php/getAJX.php",
dataType: 'json',
context: this,
data: { one: one, two: two },
success: function(data) {
this.myProperty = data[0][0];
},
error:function(request, status, error) {
console.log("Something went wrong." + request.responseText + status + error);
}
});