繁体   English   中英

在Ajax回调函数中使用JavaScript解析嵌套的json

[英]Parse nested json using javascript in ajax call back function

我有json对象

{"errorType":"ValidationError","message":null,"errors":[{"message":"may not be empty"},{"message":"may not be empty"},{"message":"may not be empty"}]}

在ajax错误回调函数中。

function makeAjaxCall(){
    var send =serializeObject($("#employee"));
    send = JSON.stringify(send); 
    $.ajax({
        url: '/RestFul-Employee/addEmployee',
        type: 'POST',
        dataType: "json",       // Accepts
        data:send, 
        contentType : "application/json",
        success: function(result) {
            alert("success");
        },

        error: function(error){ 
         //so form validation error in form     

        }
    });
}

我需要解析所有表单错误消息并以表单形式显示它们。 我无法解析错误消息。 请你帮助我好吗?

{ "errorType": "ValidationError", "message": null, "errors":[ {"message":"may not be empty"}, {"message":"may not be empty"}, {"message":"may not be empty"} ] }

如果要访问与“错误”键关联的消息数组,则可以使用.length属性循环遍历该数组,并使用.push()方法将元素添加到错误消息数组中。

var errorMessages = [];
for(var i=0; i<errorJSON.errors.length; i++){
    if( errorJSON.errors[i].message != null ){
        errorMessages.push(errorJSON.errors[i].message;
    }   
}

然后,您可以将errorMessages的索引与表单相关联。

暂无
暂无

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

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