为什么CodeIgniter的JSON响应在JavaScript中不可读?

时间:2017-11-11 17:56:55

标签: php jquery json ajax codeigniter

我使用CodeIgniter控制器将数据存储在'response'中,其中包含:

{
  "ok": false,
  "messages": {
    "cgusrnm": "<p class=\"text-danger\">The Full Name field is required.<\/p>",
    "cgnnm": "<p class=\"text-danger\">The Nick Name field is required.<\/p>",
    "cgeml": "<p class=\"text-danger\">The Email Address field is required.<\/p>",
    "cgunm": "<p class=\"text-danger\">The User Name field is required.<\/p>",
    "cgpsd": "<p class=\"text-danger\">The Password field is required.<\/p>",
    "ccgpsd": "<p class=\"text-danger\">The Confirm Password field is required.<\/p>",
    "cgcnm": "<p class=\"text-danger\">The Company Name field is required.<\/p>",
    "cgadr": "<p class=\"text-danger\">The User Address field is required.<\/p>",
    "cgct": "<p class=\"text-danger\">The City field is required.<\/p>",
    "cgcnt": "<p class=\"text-danger\">The Country field is required.<\/p>",
    "cgzn": "<p class=\"text-danger\">The State field is required.<\/p>",
    "cgzc": "<p class=\"text-danger\">The Zip Code field is required.<\/p>",
    "cgpn": "<p class=\"text-danger\">The Phone Number field is required.<\/p>",
    "cgsn": "<p class=\"text-danger\">The Skype Name field is required.<\/p>",
    "pm": "<p class=\"text-danger\">The Payment Method field is required.<\/p>",
    "cgpeml": "<p class=\"text-danger\">The Email Address field is required.<\/p>"
  }
}

但是ajax文件无法读取此数组。

我的ajax代码:

$('#form_user').submit(function(e) {
  e.preventDefault();

  var me = $(this);

  $.ajax({
    url: me.attr('action'),
    type: 'post',
    data: me.serialize(),
    datatype: 'json',
    success: function(response) {
      if (response.ok == true) {
        alert('response');
      } else {
        $.each(response.messages, function(key, value) {
          var element = $('#' + key);
          element.after(value);
        });
      }
    }
  });
});

2 个答案:

答案 0 :(得分:1)

即使数据类型是json,response变量的类型仍然是字符串。尝试添加response = JSON.parse(response);以将字符串转换为JavaScript对象。

答案 1 :(得分:0)

消息不是数组而是对象。 JSON数组看起来像{message:[“a”,“b”]}