Javascript 如何从ajax调用中获取返回值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13648995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to grab return value from an ajax call?
提问by Myke Solidum
I wanted to grab the value on an ajax call using a function. but the value always return as undefined. return value is only 1 or 0.
我想使用函数获取 ajax 调用的值。但该值总是以未定义的形式返回。返回值只有 1 或 0。
here is my code:
这是我的代码:
$(function(){
$('#add_product').click(function(){
var i = $('#product_name').val();
param = 'product_name='+i;
var value = check_product(param);
alert(value);
return false;
});
});
function check_product(param){
$.ajax({
type : 'POST',
data : param,
url : baseurl+'cart/check_product_name/',
success : function(result){
//alert(result);
return result;
}
});
}
Hi guys, still working on getting this one work. I get the value now showing 1 or 0. What im trying to accomplish now is how I can it in the if statement. I wanted to have something like this. If val = 0 return true; else return false. Im not sure I'm in the right track of using the ajax function. But if there a better way you can show me I will appreciate it.
嗨,伙计们,仍在努力让这一项工作。我现在得到的值显示为 1 或 0。我现在想要完成的是我如何在 if 语句中实现它。我想要这样的东西。如果 val = 0 返回真;否则返回假。我不确定我在使用 ajax 函数的正确轨道上。但是,如果有更好的方法可以告诉我,我将不胜感激。
$(function(){
$('#add_product').click(function(){
var i = $('#product_name').val();
param = 'product_name='+i;
check_product(param).done(function(value) {
var val = value; //waits until ajax is completed
});
if(val == 0){
return true;
} else{
return false;
}
});
});
function check_product(param){
return $.ajax({
type : 'POST',
data : param,
url : baseurl+'cart/check_product_name/'
});
}
回答by adeneo
It's asynchronous, so you have to wait for the ajax call to get the data back before you can alert it. You can do that easily by returning the ajax call and using done(), like so:
它是异步的,因此您必须等待 ajax 调用将数据取回,然后才能发出警报。您可以通过返回 ajax 调用并使用 轻松做到这一点done(),如下所示:
$(function() {
$('#add_product').click(function() {
var i = $('#product_name').val(),
par = 'product_name=' + i;
check_product(par).done(function(value) {
alert(value); //waits until ajax is completed
});
return false;
});
});
function check_product(param) {
return $.ajax({
type : 'POST',
data : param,
url : baseurl + 'cart/check_product_name/'
});
}?
回答by Igor
Add this to ajax options:
将此添加到 ajax 选项:
dataType: "json",
and use
并使用
return Json(dataObject, JsonRequestBehavior.AllowGet);
in your action method.
在您的操作方法中。
Your
您的
return result;
in the success handler of ajax is not a return for check_product. Pass another function (possibly anonymous) to check_productand call on ajax success.
在 ajax 的成功处理程序中不是check_product. 将另一个函数(可能是匿名的)传递给check_product并调用 ajax 成功。

