2012-06-04 207 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。

并使用“==”来比较,而不是“===”