-2
我在Laravel項目上使用Ajax,並且有一個按鈕會觸發具有兩個狀態錯誤和成功的函數。但是在他們兩個人身上,成功消息都會返回。Ajax調用觸發成功事件,但返回201錯誤
控制器:
if ($user->balance < $total_paid) {
return response()->json(['responseText' => 'error'], 201);
} else {
return response()->json(['responseText' => 'success!'], 200);
}
在前端
的Ajax功能:
<script type="text/javascript">
function pay_with_ewallet() {
$.ajax({
url: "{!!URL::route('pay_with_ewallet')!!}",
type: "post",
data: {
'OrderShipAddress':$('input[name=OrderShipAddress]').val(),
'_token': $('input[name=_token]').val(),
'OrderEmail':$('input[name=OrderEmail]').val(),
'city_id':$('select[name=city_id] :selected').val(),
'OrderPhone':$('input[name=OrderPhone]').val(),
'shipping_cost': @if (isset($shipping_total)) {{ $shipping_total }} @endif ,
'order_total':@if (isset($final_total)) {{ $final_total }} @endif,
},
success: function(data) {
if (response == 'success')
$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 10000);
else
$("#myerror").show();
setTimeout(function() { $("#myerror").hide(); }, 10000);
}
});
}
</script>
和按鈕:
<button href="" class="btn btn-danger pull-right" id="pay_with_ewallet-btn {{ $user->id }}" data-id="{{ $user->id }}" onclick="pay_with_ewallet('pay_with_ewallet{{ $user->id }}')">{{ trans('interface.pay_with_e_wallet') }}</button>
我試着盡我所能,並在互聯網上大量的研究但是沒用。
'201'不是錯誤的情況。 –
如上所述,201並不是一個錯誤,jQuery仍然會接受它作爲「成功」。在你的代碼的上下文中,一個403 FORBIDDEN,或者甚至只有400個BAD REQUEST似乎更合適 - 只要你提供比'error'更明確的響應 –