【问题标题】:How to get json objects from Controller in ajax如何在ajax中从Controller获取json对象
【发布时间】:2014-01-29 15:04:55
【问题描述】:

我正在用 jquery ajax 和 php 编写邮件验证控制器。

在 php 控制器中验证消息后,我试图通过 ajax 获取它并通过 jquery 在屏幕上打印。

我的 ajax 代码是这样的

....

success: function(data) {
     var jsonObj = jQuery.parseJSON(data);
        if (jsonObj.result) {
                //succes message

        }
        else {
            $.each([jsonObj.errors],function(key,value){
                console.log(jsonObj.errors);
            });

        }
    }

console.log 的错误显示:

[Object]
0: Object
email: "Email validation error message"
name: "Name validation error message"
phone: "phone validation error message"
__proto__: Object
length: 1

.......

如何获取电子邮件信息的价值以将其打印在屏幕上? 我想做类似的事情: 如果电子邮件错误不为空,则显示错误消息。

【问题讨论】:

  • 从控制器以 JSON 格式返回数据,例如:以 JSON 格式返回数据

标签: jquery ajax json


【解决方案1】:

您应该将代码更改为以下内容:

success: function(data) {
     var jsonObj = jQuery.parseJSON(data);
    if (jsonObj.result) {
            //succes message

    }
    else {
        $.each([jsonObj.errors],function(key,value){
            if (typeof jsonObj.errors[0].email !== 'undefined') {
                console.log(jsonObj.errors[0].email);
            }
        });

    }
}

【讨论】:

    【解决方案2】:

    假设您在控制器中有一个数组:

      Array
        (
            [message] => json object from controller
            [data] => Array
                (
                    [name] => user25354i
                    [profile_views] => 234
                )
    
        )
    $array = array('message'=>"json object from controller",
                   'data'=>array('name'=>'user25354i','profile_views'=>'234'));
    

    返回 $array 为:echo json_encode($array);exit;

    现在在 jQuery 中它会默认被视为 json 对象,所以你可以简单地访问这个数组,如下所示:

    success: function(response) {
         alert(response.message);
         alert(response.data.name);
         so on...
        }
    

    希望它能回答你的问题!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      • 2018-06-21
      • 2020-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多