简体   繁体   中英

Parse nested json using javascript in ajax call back function

I have json object

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

at the ajax error call back function.

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     

        }
    });
}

I need parse all form error message and show them in a form. I can not parse the error messages. Could you please help me?

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

If you want to access the array of messages associated with the "errors" key, you can use the .length property to loop over the array and add elements to an error message array using the .push() method.

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

Then you can associate the indices of the errorMessages with your form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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