Ajax л oop json ответ - PullRequest
       22

Ajax л oop json ответ

0 голосов
/ 04 августа 2020

У меня есть такие результаты, и мне нужно добавить их в моем представлении:

val: {email: Array(1), first_name: Array(1)}
    email: Array(1)
        0: "The email field is required."
        length: 1
        __proto__: Array(0)
    first_name: Array(1)
        0: "The first name field is required."
        length: 1
        __proto__: Array(0)
        __proto__: Object

код

$('#submitRegister').on('click', function(e) {
    e.preventDefault();
    $.ajaxSetup({
        headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
    });

    var formData = {};
    $('#registerForm').find("input[name]").each(function (index, node) {
        formData[node.name] = node.value;
    });

    $.ajax({
        url: '{{route('frontend.register.validate')}}',
        type: "POST",
        data: {
            "_token": "{{ csrf_token() }}",
            formData,
        },
        dataType: "json",
        success:function(data) {
            $(data.errors).each(function (index, value) {
                console.log('val: ', value);
            });
        }
    });
});

html

<div id="errors"></div>

есть идеи?

Ответы [ 2 ]

1 голос
/ 04 августа 2020

Вам нужно использовать Object.keys , затем проверить и l oop внутри каждого массива

val  = {email: ["The email field is required."], first_name: ["The first name field is required."] };


var errs = []

keys = Object.keys(val)

for(var i=0; i<keys.length;i++)
{
 
  if(Array.isArray(val[keys[i]]))
  {
    for(var j=0; j<val[keys[i]].length; j++)
      errs.push(val[keys[i]][j])
  }
  else
      errs.push(val[i])
}

var str = '';
$.each(errs, function( index, value ) {
  str += '<li>' + value + '</li>';
});

$('#msgs').html(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="msgs"></div>
0 голосов
/ 04 августа 2020

Вы можете использовать document.getElementById(), чтобы найти элемент, к которому вы хотите добавить вещи, затем вы можете использовать document.createElement (), чтобы создать элемент для добавления, а затем вы можете использовать append(), чтобы добавить его в div . Итак, все вместе:

var errors = document.getElementById('errors'); // Getting the div we want to append to
var newElement = document.createElement('h1'); // Creating the element we want to append to the errors div
newElement.textContent = value; // Setting the text value of the new element to the information we want to display
errors.append(newElement); // Appending the new element to the errors div

Вы должны иметь возможность поместить это в свою функцию .each () после console.log ().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...