jquery loop through json doesn't work as expected
Answer a question
I have a very simple ajax snippet that serializez a flask form (wtforms) and send it to an endpoint. the endpoint validates the form (wtforms validation). for now, all I need is a valid message if the form validates and a list of errors if it doesn't. this is my code:
@bp_catalogue.route('/catalogue/add_dataset', methods = ['POST'])
@login_required
def add_dataset():
form = add_dataset_form()
if form.validate_on_submit():
return jsonify(success = 'ok!')
return jsonify(error = form.errors)
This code works as expected and if all is ok, the 'ok!' string is available to me in jquery using response.success to be used as I wish. if the form doesn't validate, I expect it to send the errors back in a similar format, and it does. this is what a response looks like:

response.error contains several errors, such as a simple message saying that the empty inputs require a value. I'm looking to loop through these values and pass them on to a container under each form in my html. this is my code:
$('form').on('submit', function(event) {
$.ajax({
data : $('form').serialize(),
type : 'POST',
url : '/catalogue/add_dataset'
}).done(function(response) {
if (response.hasOwnProperty('success')) {
$('form')[0].reset();
$('.response').empty().html(response.success);
}
$(response.error).each(function(key, value) {
console.log(value);
});
});
event.preventDefault();
});
the issue is that my code to loop through the errors doesn't return what I expect it to. looking at the image, response.error is the object, with 2 elements: dataset_name and dataset_description. as I'm looping through those, I'm expecting the console to log the actual error message for each of the errors and it's not.
what am I doing wrong?
Answers
Your dataset_description and dataset_name has value as arrays so you need iterate through that array to get required values .
Demo Code :
var response = {
"error": {
"dataset_description": ["something1", "something12"],
"dataset_name": ["something02", "something13"]
}
}
//loop through error
$.each(response.error, function(key, value) {
console.log(key + " : ") //key
//loop through value
$.each(value, function(index, values) {
console.log(values); //print value at that key
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
更多推荐

所有评论(0)