我有以下javascript函数,它使用POST
数据并使用Ajax
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 response
,因此执行点将转到error: function (jqXHR, textStatus, errorThrown, data)
,在这里我想访问post_data
来显示给用户的东西....那么我们可以访问上面的ajax错误函数中的post_data
吗?
答案 0 :(得分:4)
如果有人寻找通用方法来执行此操作,请按以下步骤操作:如果定义了处理程序函数,其范围不允许您访问某些变量,则可以将它们添加到ajax对象本身在函数beforeSend
中。然后,您可以使用this
$.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>
&#13;
答案 1 :(得分:0)
function postData(post_data) {
console.log(post_data, "----------->");
// var data = post_data; // why ?
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataTpe: "json",
success: function (response) { // pay attention to args and vars naming as it makes the code easier to read
// use response
},
error: function (jqXHR, textStatus, errorThrown, data) {
// handle error
console.log(post_data); // and the magic happens
},
}
);
};
答案 2 :(得分:0)
在这个问题上面你有错误的密钥“dataType”我修改了它。其次,“post_data”在您的范围内,您可以毫无问题地访问它。
function postData(post_data) {
console.log(post_data, "----------->");
// var data = post_data; // why ?
var url = "/super/man/"
$.ajax(
{
type: "POST",
url: url,
data: post_data,
dataType: "json",
success: function (response) { // pay attention to args and vars naming as it makes the code easier to read
// use response
},
error: function ( jqXHR jqXHR, textStatus, errorThrown) {
// post data is in your scope you can easily access it
console.log(post_data); // and the magic happens
},
}
);
};