2014-02-14 49 views
5

我有一個JavaScript文件,使AJAX調用服務器上的PHP文件返回JSON編碼數據。 PHP文件可以返回成功或根據與大約十幾個不同的消息,像這樣一個錯誤:Javascript閱讀JSON結果來自AJAX響應

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." }我做錯了閱讀消息?

+1

做console.log響應(檢查是否得到響應)然後if(response.success)不做hasOwnProperty它不是必需的。 – wilsonrufus

+0

你使用哪個版本的jquery? –

+0

其最新版本的jquery,我得到的回覆 – dpegasusm

回答

3

您需要在使用前parse JSON響應,

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

OR

可以在AJAX調用中使用的數據類型屬性爲json,如:

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

更好地使用'dataType'選項。 – Bergi

+0

雅它也是一個選項... :) –

+0

@SherinJose那對我有用:)謝謝! – dpegasusm

1

只需編輯你的JavaScript代碼在最後加入數據類型(參見下面的c中的最後一個參數) ODE段) 請參考 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'); 
1

好了,你們上面已經給出了答案,但我發現更多的一個問題,在您的代碼:

我想這篇文章的語句是在事件被調用複選框的處理程序,並且您希望在響應後修改此複選框的狀態。但this對象不再是post回調函數中的複選框,它是post對象。所以你會發現你的代碼不會像你期望的那樣改變checkbox的狀態。

你可以修改你的代碼是這樣的:

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

非常感謝你!我只是想弄明白這一點! – dpegasusm

0

在ajax調用中使用dataType參數並將其設置爲json。順便說一句,你可以這樣做:

alert(response.success); 

因爲從Ajax調用或「數據」回調參數返回的對象實際上是一個JSON對象,而不是一個數組。