我想从ajax函数获取jquery ajax post请求值到外部。我的代码就是这样,它将 undefined
作为控制台输出返回。应该如何修复
function submit() {
var outputFromAjax = submitViaPost('administrator/validationForInputValuesOfAddRole');
console.log(outputFromAjax);
}
function submitViaPost(url) {
var formData = $('form').serializeArray();
var output;
$.post(urlForPhp + '/' + url, formData, function (outputData) {
output = outputData;
});
return output;
}
被修改
我将代码更改为同步类型ajax post request并检查输出。但它没有改变。这是我的代码
function submit() {
var outputFromAjax = submitViaPost('administrator/validationForInputValuesOfAddRole');
console.log(outputFromAjax);
}
function submitViaPost(url) {
var formData = $('form').serializeArray();
var output;
$.ajax({
url: urlForPhp + '/' + url,
data: formData,
dataType: 'JSON',
async: false,
method: 'POST',
success: function (e) {
output = e;
}
});
return output;
}
答案 0 :(得分:0)
不要返回,将其作为回调,因为$.post
是异步
function submit() {
submitViaPost('administrator/validationForInputValuesOfAddRole', function(out){ //Result comes here
var outputFromAjax = out;
console.log(outputFromAjax);
});
}
function submitViaPost(url , callback) { //Added callback
var formData = $('form').serializeArray();
$.ajax({
url: urlForPhp + '/' + url,
data: formData,
dataType: 'JSON',
async: false,
method: 'POST',
success: function (e) {
callback(e);
}
});
}
答案 1 :(得分:0)
您可以使用Deferred jQuery
function submit() {
submitViaPost('administrator/validationForInputValuesOfAddRole').then(function (outputFromAjax) {
console.log(outputFromAjax);
});
}
function submitViaPost(url) {
var dfd = jQuery.Deferred();
var formData = $('form').serializeArray();
$.post(urlForPhp + '/' + url, formData, function (outputData) {
dfd.resolve(outputData);;
});
return dfd;
}