2012-06-04 206 views
0

我正在處理我的類中爲ajax和普通發佈請求輸出錯誤消息的方法。 PHP部分工作正常,但json部分似乎沒有。這裏是我的方法:JSON的PHP json_encode

public $formError = false; 
public $phpErrors = ''; 
public $jsonErrors = array(); 

// ------------------------------------------------------------ 
// ERROR PROCESSING 
// ------------------------------------------------------------ 
private function responseMessage($bool, $msg) { 
    $return['error'] = $bool; 
    $return['msg'] = $msg; 
    if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) { 
     $this->jsonErrors[] = $return; 
    } else { 
     foreach ((array) $msg as $key => $value) { 
      $this->phpErrors .= $msg; 
     } 
    } 
    $this->formError = true; 
} 

我認爲,問題是,不管它僅僅是一個單一的錯誤消息或多個,JSON對象總是包裹着方括號。我找不到任何可以顯示示例的內容。這些消息是這樣的:

SINGLE ERROR:

[{ 「錯誤」:真, 「msg」 中: 「錯誤消息1 ...」}]

多個錯誤:

[{「error」:true,「msg」:「Error message 1 ...」},{「error」:true,「msg」:「Error message 2 ...」}]

Firebug shows 200 OK,但我的JQuery不輸出任何消息:

$.ajax({ 
    type: 'POST', 
    url: plSubmitUrl, 
    data: plFormData, 
    dataType: 'json', 
    cache: false, 
    timeout: 10000, 
    success: function (data) { 
     if (data.error === true) { 

      // display error message 
      plResponse(data.msg, true); 

      ... 
     } else if (data.error === false) { 

      // display success message 
      plResponse(data.msg, true); 

      ... 
     } 
    }, 

當我一次只顯示一條消息時,JQuery工作正常。

任何幫助將是偉大的。謝謝

回答

0

由於多個錯誤包含多個索引,所以它可能不會選擇數據。 檢查長度超過錯誤。

$.ajax({ 
type: 'POST', 
url: plSubmitUrl, 
data: plFormData, 
dataType: 'json', 
cache: false, 
timeout: 10000, 
success: function (data) { 
    var x = data.length; 

    if(x == 1){ 
     if (data.error === true) { 

      // display error message 
      plResponse(data.msg, true); 

     ... 
     } else if (data.error === false) { 

      // display success message 
      plResponse(data.msg, true); 
     } 
    }else{ 
     jQuery.each(data,function(key,val){ 
      // do whatever you need 
     } 

}

1

不使用全等運算符===因爲從PHP你實際上是發送字符串的instad:

if (data.error === true) 

用途:

if (data.error == true) 
0
header('Content-Type: application/json'); 

添加這是正確的首先在PHP腳本中迴應一下,讓jquery知道它必須將整個字符串解析爲JSON。

並使用「==」來比較,而不是「===」