Recover json ajax array

1

I'm trying to recover the values that passed through an array in json to ajax.

this is the code I use:

function CompletarEan(cod) {
    $.ajax({
        url: "./Scripts/Phps/Autocompletar.php?pag=autocompletar_Ean&term="+cod,
        type: "post",
        dataType: 'json',
        success: function(data) {
            $("#InAlbaran_Articulo").val(data.idean);
            $("#InAlbaran_Ean").val('');
            console.log(data.idean);

},
error: function(xhr, status, error){ $().toastmessage('showToast', { text : 'Error con ean '+ xhr.responseText, sticky : true, type : 'error' }); }
    });
}

and this is the array that json returns to me:

[{"idean":"1316","nombre":"843446300058"}]

The fact is that I would like to assign those values received to different input but I do not know why it results in undefinied.

What can I be doing wrong? or how are the values in ajax recovered?

    
asked by Killpe 04.10.2017 в 21:49
source

3 answers

2

Regards

The data you receive is an array; it will be enough for you to indicate the index you wish to access; if it is a single element:

$("#InAlbaran_Articulo").val(data[0].idean);
    
answered by 04.10.2017 / 22:04
source
4
  

and this is the array that json returns to me:   [{"idean": "1316", "name": "843446300058"}]

if you return the result in that way enclosed within [...] means that it is an array in this case you have an array of objects inside an array so I think you could, first get the position of the array and then the objects that contains

here an example:

<script type="text/javascript">
  var conten = [{"idean":"1316","nombre":"843446300058"}];
  alert(conten[0].idean);
</script>
    
answered by 04.10.2017 в 22:01
1

Using JsonEditorOnline the Json looks like this:

So you must access it in the following way:

...
success: function(data) {
        $("#InAlbaran_Articulo").val(data[0].idean);
        $("#InAlbaran_Ean").val('');
        console.log(data[0].idean);
...
    
answered by 04.10.2017 в 22:00