gpt4 book ai didi

javascript - ajax 调用忽略了我的 if 语句

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

我的页面上有一个模式,它通过 ajax 将一些数据提交到我的 Laravel 应用程序,然后对其进行验证以确保存在一个字段。

如果该字段不存在,Laravel 将返回一个带有错误状态的 json 响应。

然后我检查我的 ajax 调用的成功部分的状态,如果是这种情况则显示一条错误消息。

但是,即使我返回错误状态,我的 if 语句似乎也遗漏了这个并继续执行该语句。

完整脚本如下:

<script>
$(document).ready(function () {
$("#addShiftButton").click(function(){
$.ajax({
type: "POST",
url: "calendar/addhours",
data: {
'name':$('#name').val(),
'start_time':$('input[name=start_time]').val(),
'finish_time':$('input[name=finish_time]').val(),
'add_shift_date':$('#add_shift_date').val(),
'breaks':$('input[name=breaks]').val(),
'shift_status':$('#shift_status').val()
},
success: function(data){
if (data.status == "error")
{
$("#error").show();
}
else
{
$('#addShiftModal').modal('hide'); //hide popup
//location.reload();
}
},
error: function(){
alert("Error");
}
});
});
});
</script>

我已经检查了调用,它正在成功进行,并且收到了一个 json 响应,如下所示:{"status":"error"}

然而,我的 if 语句的 else 部分正在执行。谁能看出原因?

最佳答案

<script>
$(document).ready(function () {
$("#addShiftButton").click(function(){
$.ajax({
type: "POST",
url: "calendar/addhours",
data: {'name':$('#name').val(), 'start_time':$('input[name=start_time]').val(), 'finish_time':$('input[name=finish_time]').val(), 'add_shift_date':$('#add_shift_date').val(), 'breaks':$('input[name=breaks]').val(), 'shift_status':$('#shift_status').val()},
success: function(data){
var result = jQuery.parseJSON( data ); // you need to convert json into javascript array
if (result.status == "error")
{
$("#error").show();
}
else
{
$('#addShiftModal').modal('hide'); //hide popup
//location.reload();
}
},
error: function(){
alert("Error");
}
});
});
});

基本上您正在做的是尝试通过 data.status 访问 json 对象的成员,您必须在执行此操作之前将其转换为 javascript 对象,如上面的代码所示。

关于javascript - ajax 调用忽略了我的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35980501/

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