简体   繁体   中英

Error in getting data from ajax json response

I'm trying to get data from the JSON response from the ajax, when i try to get data outside of the loop for there is no problem(the console.log command worked), but when it's inside it gives error

TypeError: Cannot read property 'TOTALITEM' of undefined

the console.log command gave the error above.The same happened on the second for, on "orc[i].NITEM" but it worked i don't know why. I also tried to sum the values and append in a second place but it also didn't work. i would be really gratefull if someone could explain why this is happening.thanks!!

var obj= JSON.parse(data);
                var orc = obj.DADOS.ORCITENS[0].ITENSORC.LITEM;
                var tamanho = orc.length;
                var total=0;
                $(".lista-orcamento").empty();
                console.log(orc[0].TOTALITEM);
                for(var x = 0; x <= tamanho; x++)
                {
                    console.log(orc[x].TOTALITEM);
                        total+= parseFloat(orc[x].TOTALITEM);

                }
                console.log(total);

                for(var i = 0; i <= tamanho; i++)
                {
                    $(".lista-orcamento").append
                        ('<div class="row produtos" >'+
                            '<div class="col-1">'+orc[i].NITEM+'</div>'+
                             '<div class="col-1"> <input type="text" class="form-control codigo" value='+orc[i].CODPRODUTO+'></div>'+
                             '<div class="col-1"> <input type="text" class="form-control quantidade" value='+orc[i].QTDVENDIDO+'></div>'+
                             '<div class="col-3"> <input type="text" class="form-control descricao" value='+orc[i].DESCRICAO+'></div>'+
                             '<div class="col-1">'+
                             '<select  class="form-control prcu">'+
                                '<option value="001">'+orc[i].PRCUNIT+'</option>'+
                             '</select></div>'+
                             '<div class="col-1"> <input type="text" class="form-control prcv" value='+orc[i].PRCVENDA+'></div>'+
                             '<div class="col-1"> <input type="text" class="form-control desco" value='+orc[i].DESCPUNIT+'></div>'+
                             '<div class="col-1"> <input type="text" class="form-control prct" value='+orc[i].TOTALITEM+'></div>'+
                             '<div class="col-1"> <input type="text" class="form-control descot" value='+orc[i].DESCVUNIT+'></div>'+
                             '<div class="col-1"> <input type="text" class="form-control obs" value='+orc[i].OBSITEM+'></div>'+
                          '</div>'
                        );
                }// fim do for

            }//fim sucesso

If one assumes that the code you have supplied is within a success callback, it may look something like:

$.ajax({
  url: "get-orc-data.php",
  data: { id: 0 },
  dataType: "json",
  method: "post",
  success: function(data){
    // Your Code
    var obj = JSON.parse(data);
    var total = 0;
  }
});

In the example above, remember that obj and total will be defined only for the scope of that function. You can not call obj or total outside of that function. If you need that variable to be updated, create one that is in scope for a more global arena.

Consider this code:

$(function(){
  var total = 0;
  $.ajax({
    url: "get-orc-data.php",
    data: { id: 0 },
    dataType: "json",
    method: "post",
    success: function(data){
      console.log(data);
      var orc = data.DADOS.ORCITENS[0].ITENSORC.LITEM;
      $(".lista-orcamento").empty();
      console.log("Counting Total: " + total);
      $.each(orc, function(k, v){
        console.log("Adding: " + v.TOTALITEM);
        total += parseFloat(v.TOTALITEM);
      });
      console.log("Total Calculated: " + total);
      $.each(orc, function(k, v){
        $(".lista-orcamento").append(
          '<div class="row produtos" >',
          '<div class="col-1">' + v.NITEM + '</div>',
          '<div class="col-1"> <input type="text" class="form-control codigo" value=' + v.CODPRODUTO + '></div>',
          '<div class="col-1"> <input type="text" class="form-control quantidade" value=' + v.QTDVENDIDO + '></div>',
          '<div class="col-3"> <input type="text" class="form-control descricao" value=' + v.DESCRICAO + '></div>',
          '<div class="col-1">',
          '<select  class="form-control prcu">',
          '<option value="001">' + v.PRCUNIT + '</option>',
          '</select></div>',
          '<div class="col-1"> <input type="text" class="form-control prcv" value=' + v.PRCVENDA + '></div>',
          '<div class="col-1"> <input type="text" class="form-control desco" value=' + v.DESCPUNIT + '></div>',
          '<div class="col-1"> <input type="text" class="form-control prct" value=' + v.TOTALITEM + '></div>',
          '<div class="col-1"> <input type="text" class="form-control descot" value=' + v.DESCVUNIT + '></div>',
          '<div class="col-1"> <input type="text" class="form-control obs" value=' + v.OBSITEM + '></div>'+
          '</div>'
        );
      });
    }
  });
});

Now total can be used in other functions.

Also, since the $.ajax() call has the dataType defined, it should be expecting a JSON object already. Reviewing the console should confirm this as there should be an object returned with the data structure you're expecting. If you're getting something else, you will want to review the code and ensure it matches the data structure or review the API.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM