读取JSON的Javascript来自AJAX响应

时间:2022-10-09 07:42:12

I have a javascript file that makes an AJAX call to a php file on the server which returns JSON encoded data. The PHP file can return either a success or a failure depending with about a dozen different messages like so:

我有一个javascript文件,它对服务器上的php文件进行AJAX调用,该文件返回JSON编码的数据。PHP文件可以返回成功或失败,具体取决于大约12条不同的消息:

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. I am getting a response that when I console.log it looks like so: { "success", "Successfully did something." } What am i doing wrong reading the message?

问题是,无论我怎么检查成功条件总是显示错误消息的响应(错误的)定义我试着测试typeOf响应['成功']! =“定义”和许多其他方面是否成功值设置,但这似乎不能工作。我得到的回应是,当我安慰。日志看起来是这样的:{“成功”,“成功完成某事”。我读错信息了吗?

4 个解决方案

#1


3  

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");

#2


1  

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');

#3


1  

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. But the this object is no longer the checkbox in the post callback function, it's the post object. So you'll find your code won't change the status of checkbox after response as you expected.

我猜这个post语句是在复选框的事件处理程序中调用的,您希望在响应之后修改这个复选框的状态。但是这个对象不再是post回调函数中的复选框,而是post对象。因此,您将发现您的代码不会像您预期的那样在响应之后更改复选框的状态。

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");

#4


0  

Use the dataType parameter in your ajax call and set it to json. And by the way, you can just do:

在ajax调用中使用dataType参数,并将其设置为json。顺便说一下,你可以这样做:

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对象,而不是数组。

#1


3  

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");

#2


1  

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');

#3


1  

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. But the this object is no longer the checkbox in the post callback function, it's the post object. So you'll find your code won't change the status of checkbox after response as you expected.

我猜这个post语句是在复选框的事件处理程序中调用的,您希望在响应之后修改这个复选框的状态。但是这个对象不再是post回调函数中的复选框,而是post对象。因此,您将发现您的代码不会像您预期的那样在响应之后更改复选框的状态。

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");

#4


0  

Use the dataType parameter in your ajax call and set it to json. And by the way, you can just do:

在ajax调用中使用dataType参数,并将其设置为json。顺便说一下,你可以这样做:

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对象,而不是数组。