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

Shi*_*dla 1 javascript ajax jquery post

我有以下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 ?
        },
      }
    );

  };
Run Code Online (Sandbox Code Playgroud)

所以我的实际意思是,由于某种原因,服务器正在发送a 500 response,因此执行点即将到达error: function (jqXHR, textStatus, errorThrown, data),在这里我要访问post_data以向用户显示内容。...因此,我们可以访问post_data上面的内部ajax错误函数?

Kad*_*ath 5

如果有人正在寻找一种通用的方式来做到这一点,这就是我的做法:如果您的处理程序函数定义在其作用域不允许您访问某些变量的位置,则可以将它们添加到ajax对象本身中功能beforeSend。然后,您可以使用来在ajax对象中检索它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);
    },
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)