如何在验证后选择ajax响应中的元素

时间:2016-08-29 20:52:58

标签: jquery ajax select

我使用ajax从我的表单发送数据。我使用Laravel,在控制器中我使用Validator,当有类似验证错误时我返回json:



$messages = $this->getValidation('individual', $input, 0);

$validator = Validator::make($input, $rules, $messages);

if ($validator->fails()) {
    return Response::json(array(
                'success' => false,
                'errors' => $validator->getMessageBag()->toArray()

    ));
}




在我看来,我只展示了所需的部分代码:



$.ajax({
  url: form.action,
  type: form.method,
  data: $(form).serialize(),
  success: function(response) {                 

    $.each(response.errors, function (key, value) {

      $('input[name=key]').addClass('error'); //I can't get input with the same name as the key

    }}";

});




我想在json中有错误属性,选择输入,选择或textarea哪个名称与$ .each函数中的键相同,并添加错误类。

返回的数据采用以下格式:



{"success":false,"errors":{"title":["The title field is required."],"first_name":["The first name field
 is required."],"last_name":["The last name field is required."],"front_passport":["The front passport
 field is required."]}}




1 个答案:

答案 0 :(得分:1)

您正在选择名称为'key'的元素;用以下内容替换您的选择器:

 $('input[name='+key+']').addClass('error');