How do I scroll through the following array using Avascript?

Asked

Viewed 166 times

0

json

[  
   {  
      "idDisciplina":"1",
      "0":"1",
      "Nome":"Matematica",
      "1":"Matematica"
   },
   {  
      "idDisciplina":"11",
      "0":"11",
      "Nome":"Ciencia",
      "1":"Ciencia"
   }
]

script

 $.ajax({
     url: "includes/disciplina.php/",
     type: "POST",
     data: {
         id: id
     },
     success: function(json) {
         $("#idDiciplina").html("");
         console.log(json);

         $('#idDiciplina').append("<option value='' selected='selected'>Disciplinas</option>");

         for (var i = 0; i < json.length; i++) {
             $('#idDiciplina').append("<option value=" + json[0][i] + ">" + json[1][i] + "</option>");

         }

     }

 });

2 answers

2

The most semantic way is by using the .reduce(). So you go through this array and add content to an HTML string and in the end you only need to tap DOM 1 time, directly with the .html() to delete previous content and insert the new whole at once.

var json = [{ "idDisciplina": "1", "0": "1", "Nome": "Matematica", "1": "Matematica" }, { "idDisciplina": "11", "0": "11", "Nome": "Ciencia", "1": "Ciencia" }, { "idDisciplina": "12", "0": "12", "Nome": "Geologia", "1": "Geologia" }];

var html = json.reduce(function(string, obj) {
  return string + "<option value=" + obj.idDisciplina + ">" + obj.Nome + "</option>"
}, "<option value='' selected='selected'>Disciplinas</option>");

$("#idDiciplina").html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="idDiciplina"></select>

var json = [{
  "idDisciplina": "1",
  "0": "1",
  "Nome": "Matematica",
  "1": "Matematica"
}, {
  "idDisciplina": "11",
  "0": "11",
  "Nome": "Ciencia",
  "1": "Ciencia"
}, {
  "idDisciplina": "12",
  "0": "12",
  "Nome": "Geologia",
  "1": "Geologia"
}];

  • 1

    Mt good, with reduce is even better. reduce()

  • Gives this error here ó: Uncaught Typeerror: json.reduce is not a Function

1

You could do:

for (i=0 ; i<json.json.length ; i++){
     var idDisciplica = json.json[i].idDisciplina;
}
  • Uncaught Typeerror: Cannot read Property 'length' of Undefined at Object.Success (registerQuestao.php:134) at b (jquery.js:109) at Xmlhttprequest.x.onreadystatechange (jquery.js:114) Success @cadastral.php:134 b @jquery.js:109 x.onreadystatechange @jquery.js:114 Xmlhttprequest.send (async) ajax @jquery.js:115 run @ cadastre Questao.php:120 [email protected]:65 Listpicker. _handleMouseUp @ about:Blank:547 !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.