簡體   English   中英

Javascript從AJAX響應讀取JSON結果

[英]Javascript Reading JSON result from AJAX response

我有一個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;   

我前端有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"] );
    }
});

問題是,無論我如何檢查成功條件,它總是顯示帶有undefined response['error']的錯誤消息,我已嘗試測試typeOf response['success'] != "undefined"和一個數字其他方法來查看是否設置了成功值,但似乎無濟於事。 我得到的響應是,當我console.log時,它看起來像這樣: { "success", "Successfully did something." } { "success", "Successfully did something." }我在做什么錯誤閱讀郵件?

您需要在使用前解析 JSON響應,

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

要么

您可以在AJAX調用中將datatype屬性用作json ,例如:

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

只需在末尾添加數據類型即可編輯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');

好吧,上面的家伙給出了答案,但是我發現您的代碼中還有一個問題:

我猜這個post語句是在復選框的事件處理程序中調用的,您想在響應后修改此復選框的狀態。 但是, this對象不再是post回調函數中的復選框,而是post對象。 因此,您會發現代碼在響應后不會像預期的那樣更改復選框的狀態。

您可以這樣修改代碼:

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

編輯:

好的,上面的代碼不夠優雅,無法引入不必要的局部變量,並且回調函數必須將父函數的局部變量保留在內存中(作為關閉的結果),因此以下是更好的選擇:

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

在ajax調用中使用dataType參數,並將其設置為json。 順便說一句,您可以執行以下操作:

alert( response.success );

由於從ajax調用或“ data”回調參數返回的對象實際上是json對象,而不是數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM