我有以下PHP数组,我将其编码为JSON,如下面的代码片段所示:
$user_info = [
"user_name" => $current_user->user_login,
"user_email" => $current_user->user_email,
"user_id" => $current_user->ID,
"user_comment" => $message
];
json_encode( $user_info );
当我运行
console.log()
编码的
$user_info
变量,我得到下面的JSON:
{
"user_name": "admin",
"user_email": "[email protected]",
"user_id": 1,
"user_comment": ""
}
我现在的问题是,当我缩小到
user_name
值,我得到一个未定义错误。
以下是我的方法:
// response is a declared variable which holds the encoded $user_info PHP array above
console.log( data.user_name );
下图是我的浏览器截图,显示了我的控制台。
这里是我的PHP代码(用黄色圈起来,是关于我帖子的实际部分)。
我的完整JavaScript代码如下:
$("#txt-cmt").keypress(function(e) {
if (e.which == 13) {
var comment = $(this).val();
var message = {
action: \'show_comment\',
user_message: comment
};
$.post(ajaxUrl.url, message, function(data) {
console.log(data.user_name);
});
}
});
我可能做错了什么,如何修复它以使代码按预期工作?
SO网友:nyedidikeke
首先需要分析data
在你拿到user_name
.
下面是一个带注释的片段,可供您浏览:
jQuery( document ).ready(function( $ ) {
console.log( "ready!" );
$( "#txt-cmt" ).keypress(function( e ) {
if ( e.which == 13 ) {
var comment = $( this ).val();
var message = {
action: \'show_comment\',
user_message: comment
};
$.post(ajaxUrl.url, message, function( data ) {
// Your data in it\'s raw form
// Expected result: {"user_name": "admin", "user_email":"[email protected]", "user_id": 1,"user_comment": ""}
console.log( "raw data" );
console.log( data );
// Here, declare a new variable to hold your parsed data
// Expected result: a JSON object {user_name: "admin", user_email: "[email protected]", user_id: 1, user_comment: ""}
var parseData = JSON.parse( data );
console.log( "parse data" );
console.log( parseData );
// After that, you can get your user_name using either of the options below;
// they both work
// Option one
// Expected result: admin
console.log( "option one" );
console.log( parseData.user_name );
// Option two
// Expected result: admin
// console.log( "option two" );
// console.log( parseData[\'user_name\'] );
})
.done(function( data ) {
// What to do after the post is successful goes here
console.log( "sort of a second success" );
})
.fail(function( data ) {
// What to do only if an error occurred goes here
console.log( "an error occurred" );
})
.always(function( data ) {
// What to always do, whether the post was successful or an error occurred goes here
console.log( "the post request has finished running, whether with a success or failure" );
});
}
});
});