简单的PHP到Ajax'未登录'错误-如何
Simple PHP to Ajax 'not logged in' error - how?
目前我正在使用它将成功或失败发送到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')});
相关文章:
- Phonegap:获取访问令牌时出现LinkedIn登录错误
- 检查登录错误Android WebView Javascript
- 类型错误:布尔值不是 Angular 中登录函数的函数
- 登录时显示自定义错误消息
- 使用PayPal按钮登录 JavaScript 代码生成器验证错误
- Facebook javascript sdk 基本登录或初始化错误
- Ajax在登录表单中显示错误,而不重新加载页面
- Google Plus登录-未知RPC服务错误
- 简单的PHP到Ajax'未登录'错误-如何
- 检查数据库后,如何在同一表单上显示登录错误消息
- 尝试使用Fancybox / Ajax处理登录错误
- 平均堆栈登录错误:未提供令牌
- 谷歌登录错误-gapi.client.plus未定义
- IE中的Facebook javascript登录错误
- AWS Cognito未认证登录错误(窗口未定义)[JS]
- 在FB.int()之前调用了facebook登录错误FB.login()
- Firebase项目导致“认证/网络请求失败”;登录错误
- 流星Facebook登录错误帐户.LoginCancelledError:没有匹配的登录尝试
- React Native + Firebase 登录错误:Undefind 不是对象(评估 'this.props.na
- AJAX/PHP登录-错误消息不工作