如何在响应时处理ajax错误

How to handle ajax errors on response.

本文关键字:处理 ajax 错误 响应      更新时间:2023-09-26

我有一个单页订单。用户填写我们的表单,javascript验证所有内容,如果它通过了ajax请求,将在客户点击提交时通过Stripe向服务器收费。

如果充电成功,json将返回到ajax请求({success:true})。然后,用户被重定向到一个成功页面,或者如果在给卡充电时发生了什么事情,则会显示一个错误。

我试图处理一个(罕见的)问题,即用户的请求到达服务器,用户成功收费,但在响应时,用户收到错误(很可能是移动/不稳定连接上的超时错误)。如何防止用户被双重收费?下面是我的ajax请求,但也许我需要重新思考我的整个基础架构?

$.ajax({ type : 'POST',
url      : '/order',
data     : $(':input').serialize(),
timeout  : 30000,
dataType : 'json',
success : function (data) {
  // redirect user to success page
  window.location = '/completed';
},
error: function(xhr,status,error) {
  // report the error to user. 
} });

试试这个。。

$.ajaxSetup({ 
type     : 'POST',
url      : '/order',
data     : $(':input').serialize(),
timeout  : 30000,
dataType : 'json',
success : function (data) {
  // redirect user to success page
  window.location = '/completed';
},
error: function(xhr,status,error) {
  if (xhr.status == 408) {//For Timeout
                alert("Sorry, Request timeout.!");
                window.location.href ="//specify a redirect url//";
            }
            else {
                alert("An error occurred: " + status + "nError: " + error);
            }
} });