Как я могу получить значения каждого элемента JSON файла - PullRequest
1 голос
/ 22 апреля 2020

Я создал это из сервлета и передал его через response.setContentType ("application / json"); Json file:

   [
      {
        "id": "1",
        "tsnm": "John1",
        "userId": "RoySoha",
        "date": "2020-04-22",
        "Button": "<button type='button'  id='opener' class='btn btn-warning'><i class='fa fa-pencil' aria-hidden='true'></i></button> &nbsp&nbsp <button type='button' id='sure' class='btn btn-danger'><i class='fa fa-trash' aria-hidden='true'></i></button>"
      },
      {
        "id": "2",
        "tsnm": "John2",
        "userId": "RoySoha",
        "date": "2020-04-22",
        "Button": "<button type='button'  id='opener' class='btn btn-warning'><i class='fa fa-pencil' aria-hidden='true'></i></button> &nbsp&nbsp <button type='button' id='sure' class='btn btn-danger'><i class='fa fa-trash' aria-hidden='true'></i></button>"
      },
      {
        "id": "3",
        "tsnm": "John3",
        "userId": "RoySoha",
        "date": "2020-04-22",
        "Button": "<button type='button'  id='opener' class='btn btn-warning'><i class='fa fa-pencil' aria-hidden='true'></i></button> &nbsp&nbsp <button type='button' id='sure' class='btn btn-danger'><i class='fa fa-trash' aria-hidden='true'></i></button>"
      }
    ]

Мой код: теперь, когда я пытаюсь получить доступ к JSON, он возвращает мне только каждое значение массива, например

{"id":"1","tsnm":"John1","userId":"RoySoha","date":"2020-04-22","Button":"<button type='button'  id='opener' class='btn btn-warning'><i class='fa fa-pencil' aria-hidden='true'></i></button> &nbsp&nbsp <button type='button' id='sure' class='btn btn-danger'><i class='fa fa-trash' aria-hidden='true'></i></button>"}

Итак, как Могу ли я получить ID, TSNM значения по отдельности? "id" = 1, "tsnm" = "John1" et c

$('#apps').change(function(event) { 
             var id = $("select#apps").val();

             $.get('PopulateTableController', {
                 ApplicationId : id
             }, function(response) {
                console.log(response);
                //$.getJSON(response, function(data){
                    alert("from json");
                    var ed = '';
                    //data = JSON.parse(response);
                    //console.log(data);
                    $(response).each(function(key, value){
                        console.log(value)
                        var x1 = value.id;var x2 = value.tsnm;var x3 = value.userId;var x4 = value.date;var x5 = value.Button;
                        console.log(x1);
                    });
                    $('.tab').append(ed);
                    console.log(ed);
                //});
         });
         });

Мне нужно каждое из значений ID, tsnm et c. Можете ли вы помочь мне?

Ответы [ 2 ]

1 голос
/ 22 апреля 2020

Вы размещаете объект response внутри объекта jQuery, чтобы выполнить итерацию по нему. Не делай этого. Просто используйте forEach() l oop:

// mock AJAX callback:
let response = [
  { "id": "1", "tsnm": "John1", "userId": "RoySoha", "date": "2020-04-22", "Button": " &nbsp&nbsp " }, 
  { "id": "2", "tsnm": "John2", "userId": "RoySoha", "date": "2020-04-22", "Button": " &nbsp&nbsp " }, 
  { "id": "3", "tsnm": "John3", "userId": "RoySoha", "date": "2020-04-22", "Button": " &nbsp&nbsp "}
]

response.forEach(value => {
  var x1 = value.id;
  var x2 = value.tsnm;
  var x3 = value.userId;
  var x4 = value.date;
  var x5 = value.Button;
  console.log(x1, x2, x3, x4, x5);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Обновление на основе комментариев ниже

Когда я печатаю значение ответа на консоли, оно выглядит как это:
["{" id ":" 1 "," tsnm ":" John1 "," userId ":" RoySoha "," date "… = 'fa fa-tra sh' aria-hidden = 'true'> "}", "{" id ":" 2 "," tsnm ":" John2 "," userId ":" RoySoha "," date "… = 'fa fa-tra sh' aria -hidden = 'true'> "}", "{" id ":" 3 "," tsnm ":" John3 "," userId ":" RoySoha "," date "… = 'fa fa-tra sh 'aria-hidden =' true '> "}"]

Незначительное, но очень важное отличие состоит в том, что ответом является массив, содержащий несколько строк в кодировке JSON. Вам необходимо декодировать каждую из них, прежде чем работать с ними. Попробуйте это:

// mock AJAX callback:
let response = [
  '{"id":"1","tsnm":"John1","userId":"RoySoha","date":"2020-04-22","Button":"your HTML..."}', 
  '{"id":"2","tsnm":"John2","userId":"RoySoha","date":"2020-04-22","Button":"your HTML..."}',
  '{"id":"3","tsnm":"John3","userId":"RoySoha","date":"2020-04-22","Button":"your HTML..."}'
]

response.forEach(json => {
  let value = JSON.parse(json);
  var x1 = value.id;
  var x2 = value.tsnm;
  var x3 = value.userId;
  var x4 = value.date;
  var x5 = value.Button;
  console.log(x1, x2, x3, x4, x5);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
0 голосов
/ 22 апреля 2020

Если ваша JSON длина массива объектов фиксирована. Вы можете использовать

var data =  [ { "id": "1", "tsnm": "John1", "userId": "RoySoha", "date": "2020-04-22", "Button": " &nbsp&nbsp " }, { "id": "2", "tsnm": "John2", "userId": "RoySoha", "date": "2020-04-22", "Button": " &nbsp&nbsp " }, { "id": "3", "tsnm": "John3", "userId": "RoySoha", "date": "2020-04-22", "Button": " &nbsp&nbsp " } ];

console.log(data[0].id);

Если JSON длина массива объекта является динамической c

var data =  [ { "id": "1", "tsnm": "John1", "userId": "RoySoha", "date": "2020-04-22", "Button": " &nbsp&nbsp " }, { "id": "2", "tsnm": "John2", "userId": "RoySoha", "date": "2020-04-22", "Button": " &nbsp&nbsp " }, { "id": "3", "tsnm": "John3", "userId": "RoySoha", "date": "2020-04-22", "Button": " &nbsp&nbsp " } ];


$(data).each(function(key, value){
    var temp_data = value;
    console.log('Index value No :' + key);
    console.log('ID = ' + temp_data.id);
    console.log('TSNM = ' + temp_data.tsnm);
    console.log('User ID = ' + temp_data.userid);
    console.log('Date = ' + temp_data.date);
    console.log('Button Value = ' + temp_data.Button);
    console.log('----------------------------------------------');
});
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...