目前我正在使用它向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 响应的情况下 die() 函数?我如何告诉 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 returned array('loggedIn' => value);
关于javascript - 简单 PHP 到 Ajax 'not logged in' 错误 - 如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20075497/