gpt4 book ai didi

javascript - 从 ajax 错误函数内部访问发布数据

转载 作者:行者123 更新时间:2023-11-30 08:25:11 24 4
gpt4 key购买 nike

我有下面的 javascript 函数,它获取 POST 数据并使用 Ajax 将 post 请求发送到服务器

function postData(post_data) {
console.log(post_data, "----------->");
var data = post_data;
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataTpe: "json",
success: function (data) {
debugger;
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
// Can we access the post_data inside this error function ?
},
}
);

};

所以我的实际观点是,由于某种原因,服务器正在发送 500 响应,因此执行点将到达 error: function (jqXHR, textStatus, errorThrown, data ),这里我想访问 post_data 来向用户显示一些东西....那么我们可以在上面的 ajax 错误函数中访问 post_data 吗?

最佳答案

万一有人寻找一种通用的方法来做到这一点,我是这样做的:如果你的处理函数定义在它们的范围不允许你访问某些变量的地方,你可以将它们添加到 ajax 对象本身在函数 beforeSend 中。然后,您可以使用 this 在 ajax 对象中检索它。

$.ajax({
url:'/dummyUrl',
beforeSend: function(jqXHR, plainObject){
plainObject.originalUrl = 'myValue';
},
success: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
$('#myValue').html(this.originalUrl);
},
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">waiting result</div>
<div id="myValue"></div>

关于javascript - 从 ajax 错误函数内部访问发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46885156/

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