Javascript从AJAX响应中读取JSON结果

dpe*_*usm 5 javascript php ajax jquery json

我有一个javascript文件,它对服务器上的php文件进行AJAX调用,返回JSON编码数据.PHP文件可以返回成功或失败,具体取决于十几种不同的消息,如下所示:

if ( something here ) {
    if( something else here ) {
        if( more tests here ) {
            $response['success'] = 'Successfully did something.';
        } else {
            $response['success'] = 'Successfully made this work';
        }
    } else {
        $response['error'] = 'Failed to make the donuts.';  
    }
} else {
    $response['error'] = 'I need more information!';
}
echo json_encode($response);
exit;   
Run Code Online (Sandbox Code Playgroud)

我在前端有javascript/jquery,它检查响应失败情况并显示警告框并执行一些其他相关操作.

$.post(ajaxurl, data, function(response) {
    if( response.hasOwnProperty("success") ) {
        if( $(this).is( ":checked" ) ) {
            $(this).removeAttr( "checked" );
        } else {
            $(this).attr( "checked", "true" );
        }
        alert( response["success"] );
    } else {
        alert( "Sorry, something went wrong.  \nError: " + response["error"] );
    }
});
Run Code Online (Sandbox Code Playgroud)

问题是,无论我如何检查成功条件,它总是会显示错误消息,其中response['error']包含undefined我尝试过的测试typeOf response['success'] != "undefined"以及其他一些方法,以查看是否设置了成功值,但似乎没有任何效果.我收到一个回复​​,当我在console.log时看起来像是这样:{ "success", "Successfully did something." }我在读错时做错了什么?

She*_*ose 3

使用前需要解析JSON 响应,

$.post(ajaxurl, data, function(response) {
    var response=JSON.parse(response);
    //then your code
});
Run Code Online (Sandbox Code Playgroud)

或者

json您可以像在 AJAX 调用中一样使用 datatype 属性,如下所示:

$.post(ajaxurl, data, function(response) {
     //your code
}, "json");
Run Code Online (Sandbox Code Playgroud)