gpt4 book ai didi

javascript - jsCall 将值返回到 jquery ajax post 请求之外

转载 作者:行者123 更新时间:2023-11-28 07:21:34 29 4
gpt4 key购买 nike

我想从 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 请求并检查输出。但它并没有改变。这是我的代码

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;
}

最佳答案

您可以使用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;
}

关于javascript - jsCall 将值返回到 jquery ajax post 请求之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30253761/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com