目前,我正在使用它将成功或失败发送到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);有些例子会有很大帮助。提前谢谢你!
发布于 2013-11-19 15:37:21
这应该是可行的:
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);相同
发布于 2013-11-19 15:44:59
您可以使用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')});https://stackoverflow.com/questions/20075497
复制相似问题