我想创建一个 JavaScript对象,如下所示。
if ($_POST['answer'] == $_POST['answer-hidden']) {
$user_name = $wpdb->escape($_POST['username']);
$user_email = $wpdb->escape($_POST['email']);
$password = $wpdb->escape($_POST['pwd']);
$confirm_password = $wpdb->escape($_POST['confirm']);
$user_id = username_exists( $user_name );
if (!$user_id and email_exists($user_email) == false and !empty($user_email) and !empty($user_name) and is_email($user_email)) {
$user_id = wp_create_user( $user_name, $password, $user_email );
$from = get_option('admin_email');
$headers = 'From: '.$from . "\r\n";
$subject = "Registration successful";
$msg = "Registration successful \n Your login details \n Username: $user_name \n Password: $password \n $login";
$headers2 = 'From: '.$user_email . "\r\n";
$subject2 = "New user register on your website.";
$msg2 = "New user register on your website \n User details are \n Username: $user_name \n Email: $user_email";
wp_mail( $user_email, $subject, $msg, $headers);
wp_mail( $from, $subject2, $msg2, $headers2);
$login_data = array();
$login_data['user_login'] = $user_name;
$login_data['user_password'] = $password;
$user_verify = wp_signon( $login_data, false );
// wp_signon is a wordpress function which authenticates a user. It accepts user info parameters as an array.
if (isset($_POST['op-register'])) {
if ($_POST['submit'] == 'Register') {
if (is_wp_error($user_verify)) {
$UserError = __('Invalid username or password. Please try again!','agrg');
} else {
echo $profile;
global $redux_demo;
$profile = $redux_demo['profile'];
wp_redirect( $profile );
}
}
}
}
}
为此,我开发的js函数如下。
var codropsEvents = {
'02-02-2017' : '<span>Some txt from database</span><span>Some txt from database</span>',
'02-05-2017' : '<span>Some txt from database</span><span>Some txt from database</span>'
};
calendarData.php 文件生成以下字符串(包括所有冒号,逗号,标签等)
function setEventsCalendar() {
var codropsEvents
try {
$.ajax({
type: "POST",
url: "calendarData.php",
dataType: "text",
async: false,
success: function(msg) {
codropsEvents = "{" + msg + "}";
codropsEvents = JSON.parse(codropsEvents);
}
});
return codropsEvents;
} catch(ex) {
alert(ex);
}
}
var codropsEvents = setEventsCalendar();
如何使用该String创建JS对象?或任何其他适当的方式来获得预期的结果。
答案 0 :(得分:1)
你可以在php-
中创建一个数组$dataArray = ['02-02-2017' => '<span>Some txt from database</span><span>Some txt from database</span>',
'02-05-2017' => '<span>Some txt from database</span><span>Some txt from database</span>'];
// and this array to json string and print it,
echo json_encode($dataArray,JSON_FORCE_OBJECT);
现在在ajax部分,您可以通过将dataType更改为json
来简单地获取json格式的数据;成功函数的msg参数是javascript对象,或者在成功函数中有codropsEvents = JSON.parse(msg);
之类的代码。