目前我正在使用它将成功或失败发送到ajax:
$response = array( 'success' => true );
wp_send_json_success($response);
然而,假设用户没有登录,我想在那里结束php函数,并发送错误消息,提示弹出登录模式。我该怎么做?类似:
if(!is_user_logged_in)) {
wp_send_json_error('not logged in');
die()
}
或者我可以使用更常见的json_encode($response);
if(!is_user_logged_in)) {
echo json_encode($response);
die()
}
但是这个处理程序怎么会知道发生了错误呢?如果我把所有成功和错误的选项都放在一个数组中,我如何在返回json响应的同时终止()函数?以及如何告诉php发送哪个响应?
一旦它到达我的ajax调用,我相信我能解决它。我读到的是这样的东西:
var dataArray = jQuery.parseJSON(data);
一些例子会有很大的帮助。提前谢谢!
这应该有效:
if(!is_user_logged_in()) {
$response = array(
'loggedIn' => false,
'alertMsg' => 'not logged in :,-(',
);
} else {
$response = array(
'loggedIn' => true,
'success' => true,
'alertMsg' => 'test!',
);
}
wp_send_json_success($response);
die();
Ajax调用类似于:
jQuery.get('pathToYourJsonFunctionURL', function(data) {
if (data.loggedIn == true) {
jQuery('#divForLoggedInStatus').text('You are logged in');
} else {
jQuery('#divForLoggedInStatus').text('You are NOT logged in');
}
window.alert(data.alertMsg);
});
当您返回JSON数据时,您不使用parseJSON
(数据已经(解析)为JSON)。data.loggedIn
与PHP中返回的array('loggedIn' => value);
相同
您可以使用json_encode并制作自己的协议,如下所示:
if(isset($_POST['operation']) && $_POST['operation'] == 'is_user_logged_in'){
if(!is_user_logged_in()){
$response->success = false;
$response->msg = "not logged in";
}else{
$response->success = true;
}
echo json_encode($response);
exit;
}
然后在您的ajax中:
$.post('AJAX-URL-HERE',{"operation":"is_user_logged_in"},function(response){
if(response.success){
//do whatever
}else{
var message = response.msg
//pop up the login modal
}
},'json').error(function(){alert('Call error')});