简体   繁体   English

Javascript从AJAX响应读取JSON结果

[英]Javascript Reading JSON result from AJAX response

I have a javascript file that makes an AJAX call to a php file on the server which returns JSON encoded data. 我有一个JavaScript文件,该文件对服务器上的php文件进行AJAX调用,该文件返回JSON编码的数据。 The PHP file can return either a success or a failure depending with about a dozen different messages like so: 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;   

I have javascript/jquery on the front end that is checking for the response failure condition and displaying an alert box and performing some other relevent actions depending. 我前端有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"] );
    }
});

The problem is that no matter how i check for the success condition it always displays the error message with a response['error'] of undefined I've tried testing for typeOf response['success'] != "undefined" and a number of other ways to see if the success value is set but nothing seems to work. 问题是,无论我如何检查成功条件,它总是显示带有undefined response['error']的错误消息,我已尝试测试typeOf response['success'] != "undefined"和一个数字其他方法来查看是否设置了成功值,但似乎无济于事。 I am getting a response that when I console.log it looks like so: { "success", "Successfully did something." } 我得到的响应是,当我console.log时,它看起来像这样: { "success", "Successfully did something." } { "success", "Successfully did something." } What am i doing wrong reading the message? { "success", "Successfully did something." }我在做什么错误阅读邮件?

You need to parse JSON response before use, 您需要在使用前解析 JSON响应,

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

OR 要么

You can use the datatype property as json in the AJAX call like: 您可以在AJAX调用中将datatype属性用作json ,例如:

$.post(ajaxurl, data, function(response) {
     //your code
}, "json");

Simply Edit your code of the JavaScript by adding Data Type in the end (see last parameter in the following code snippet) please refer https://api.jquery.com/jQuery.post/ 只需在末尾添加数据类型即可编辑JavaScript代码(请参见以下代码段中的最后一个参数),请参阅https://api.jquery.com/jQuery.post/

$.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"] );
    }
},'json');

Well, the guys above have given the answer, but I have found one more problem in your code: 好吧,上面的家伙给出了答案,但是我发现您的代码中还有一个问题:

I guess this post statement is invoked in a event handler of a checkbox and you want to modify the status of this checkbox after response. 我猜这个post语句是在复选框的事件处理程序中调用的,您想在响应后修改此复选框的状态。 But the this object is no longer the checkbox in the post callback function, it's the post object. 但是, this对象不再是post回调函数中的复选框,而是post对象。 So you'll find your code won't change the status of checkbox after response as you expected. 因此,您会发现代码在响应后不会像预期的那样更改复选框的状态。

Your can modify your code like this: 您可以这样修改代码:

var $ele = $(this);
$.post(url, data, function() {
...
if( $(this).is( ":checked" ) ) {
            $ele.removeAttr( "checked" );
        } else {
            $ele.attr( "checked", "true" );
        }
...
}, "json");

Edit: 编辑:

Well, the code above is not elegant enough for introducing an unnecessary local variable and the callback function has to keep the local variables of the parent function in memory(as a result of closure), so the following is a better choice: 好的,上面的代码不够优雅,无法引入不必要的局部变量,并且回调函数必须将父函数的局部变量保留在内存中(作为关闭的结果),因此以下是更好的选择:

$.post(url, data, $.proxy(function() {
...
//use "this" object just like the original code of author
...
}, this), "json");

Use the dataType parameter in your ajax call and set it to json. 在ajax调用中使用dataType参数,并将其设置为json。 And by the way, you can just do: 顺便说一句,您可以执行以下操作:

alert( response.success );

Since the returned object from ajax call or the "data" callback parameter is actually a json object, not an array. 由于从ajax调用或“ data”回调参数返回的对象实际上是json对象,而不是数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM