简体   繁体   English

CodeIgniter-Jquery Ajax-解析从Ajax调用收到的Json

[英]CodeIgniter - Jquery Ajax - Parse Json Received From Ajax Call

I have an issue with parsing json in my success function (ajax). 我在成功函数(ajax)中解析json时遇到问题。 I am now starting to learn json properly, but I simply can't get this to work. 我现在开始正确地学习json,但是我根本无法使它正常工作。

I have this jquery function to submit data: 我有这个jQuery函数来提交数据:

$("#loginForm").on('submit', function(form)
{   
    form.preventDefault();
    var tdata= $("#loginForm").serializeArray();
    var that = $(this),
    data = tdata;

    $.ajax({
        url: that.attr('action'),
        type: 'POST',
        data: data,

        success: function(data){

            alert(data["error"]["email"]);
        },
        error: function(){
            alert(data["error"]["email"]);
        }
    });

 });

In the controller I have this: 在控制器中,我有这个:

$this->load->library('form_validation');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim|xss_clean');
        $this->form_validation->set_rules('password', 'Password', 'required');
 .....
$arrReturnData['error'] = $this->form_validation->error_array();
 echo json_encode($arrReturnData);

In firefox when I trace the requests, the string received is: 在firefox中,当我跟踪请求时,收到的字符串是:

{"error":{"email":"The Email field is required.","password":"The Password field is required."}}

But I cannot parse it :( I don't know how, and I've spent more than 3 hours just on this part. Everything works just that I can't parse this. 但是我不能解析它:(我不知道如何,我在这部分上花了3个多小时。一切正常,我无法解析。

I tried like: 我尝试过:

data.error["email"]

or 要么

data[0]["email"]

But It fails to get the email error message. 但是它无法获取电子邮件错误消息。 Please help :) 请帮忙 :)

I found a solution. 我找到了解决方案。 I couldn't manage to work with the data variable. 我无法处理数据变量。 What I did, is modified the error function (jquery ajax) like this: 我所做的是修改错误函数(jquery ajax),如下所示:

error: function(request, status, error){
                var json=request.responseText;
                obj = JSON && JSON.parse(json) || $.parseJSON(json);
                alert(obj.error.email);

            }

So I use JSON.parse of the request.responseText. 所以我使用request.responseText的JSON.parse。 And now I can successfully use obj.error.email 现在我可以成功使用obj.error.email

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM