【发布时间】:2021-02-17 19:24:58
【问题描述】:
假设我有以下功能。 alert_danger 返回红色框内的错误信息。 check_empty 检查从表单发布的值是否为空。
function alert_danger($msg){
$alert = "<div class='alert alert-danger' id='responseBox'>".$msg."</div>";
return $alert;
}
function checkEmpty($postValue, $msg){
if($postValue == null){
echo alert_danger($msg);
exit();
}
}
现在,当我想使用 JSON 返回函数值时,它返回的不是相同的值。出现以下错误:
// It returns this
$msg = alert_danger("Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
// But it does not returns this
$msg = checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
这里似乎有什么问题?
如果需要,这是我的 jQuery!
$(".action").click(function() {
var form = $(this).closest("form");
var type = form.find(".type").val();
var dataString = form.serialize();
var btnValue = $(".action").html();
var btnElement = $(".action");
var url = form.attr("action");
$.ajax({
type: "POST",
dataType : "json",
url: url,
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$(".overlay").show();
$(".wickedpicker").hide();
btnElement.html('Please wait...');
},
success: function(json){
$('.message').html(json.status).fadeIn();
// $('#content').html(json.result).fadeIn();
$(".overlay").hide();
$("html, body").animate({ scrollTop: $(".message").offset().top }, "slow");
btnElement.html(btnValue);
if(type == 'admin'){
if($('.message').find('#responseBox').hasClass('alert-success')){
setTimeout(function(){
$(".overlay").hide();
window.location.replace("dashboard.php");
}, 1000);
}
}
}
});
return false;
});
【问题讨论】:
-
alert_danger函数在哪里?你怎么打电话给checkEmpty?但是checkEmpty没有返回任何值......所以分配$msg = checkEmpty是没有意义的 -
alert_danger是否返回值? -
你的函数没有
return任何内容。这将使$msg成为null -
@ProfessorAbronsius 我已经更新了这个问题。请检查。我以为我不需要在那里提到
alert_danger()函数所以我没有,但既然你要求它,我已经更新了它。 -
@Twisty 我的函数确实返回了一个值。当我不使用 JSON 时,一切都运行良好。但如果我使用 JSON,那么它不会返回任何值。
标签: php jquery json ajax function