Pergunta

Estou retornando um List <> de um webservice como uma lista de objetos JSON. Eu estou tentando usar um loop for para percorrer a lista e pegar os valores fora das propriedades. Esta é uma amostra do JSON retorno:

{"d":[{"__type":"FluentWeb.DTO.EmployeeOrder",
 "EmployeeName":"Janet Leverling",
 "EmployeeTitle":"Sales Representative",
 "RequiredDate":"\/Date(839224800000)\/",
 "OrderedProducts":null}]}

Então, eu estou tentando extrair o conteúdo usando algo parecido com isto:

function PrintResults(result) {

for (var i = 0; i < result.length; i++) { 
    alert(result.employeename);
}

Como isso deve ser feito?

Foi útil?

Solução

teve mesmo problema hoje, Seu tópico ajudou-me então aqui vai solução;)

 alert(result.d[0].EmployeeTitle);

Outras dicas

Tenha cuidado, d a lista.

for (var i = 0; i < result.d.length; i++) { 
    alert(result.d[i].employeename);
}

É perto! Tente isto:

for (var prop in result) {
    if (result.hasOwnProperty(prop)) {
        alert(result[prop]);
    }
}

Update:

Se o resultado é realmente é uma matriz de um objeto, então você pode ter que fazer isso:

for (var prop in result[0]) {
    if (result[0].hasOwnProperty(prop)) {
        alert(result[0][prop]);
    }
}

Ou se você quiser percorrer cada resultado na matriz se houver mais, tente:

for (var i = 0; i < results.length; i++) {
    for (var prop in result[i]) {
        if (result[i].hasOwnProperty(prop)) {
            alert(result[i][prop]);
        }
    }
}

Aqui está:

success: 
    function(data) {
        $.each(data, function(i, item){
            alert("Mine is " + i + "|" + item.title + "|" + item.key);
        });
    }

Amostra de texto JSON:

{"title": "camp crowhouse", 
"key": "agtnZW90YWdkZXYyMXIKCxIEUG9zdBgUDA"}

Uma vez que você estiver usando jQuery, assim como você pode usar o método each ... Além disso, parece que tudo é um valor da propriedade 'd' neste objeto JS [notação].

$.each(result.d,function(i) {
    // In case there are several values in the array 'd'
    $.each(this,function(j) {
        // Apparently doesn't work...
        alert(this.EmployeeName);
        // What about this?
        alert(result.d[i][j]['EmployeeName']);
        // Or this?
        alert(result.d[i][j].EmployeeName);
    });
});

Isso deve funcionar. se não, então talvez você pode nos dar uma maior exemplo do JSON.

Editar: Se nada disso funcionar, então eu estou começando a pensar que poderia haver algo de errado com a sintaxe do seu JSON.

var d = $.parseJSON(result.d);
for(var i =0;i<d.length;i++){
    alert(d[i].EmployeeName);
}

Este trabalho vontade!

$(document).ready(function ()
    {
        $.ajax(
            {
            type: 'POST',
            url: "/Home/MethodName",
            success: function (data) {
                //data is the string that the method returns in a json format, but in string
                var jsonData = JSON.parse(data); //This converts the string to json

                for (var i = 0; i < jsonData.length; i++) //The json object has lenght
                {
                    var object = jsonData[i]; //You are in the current object
                    $('#olListId').append('<li class="someclass>' + object.Atributte  + '</li>'); //now you access the property.

                }

                /* JSON EXAMPLE
                [{ "Atributte": "value" }, 
                { "Atributte": "value" }, 
                { "Atributte": "value" }]
                */
            }
        });
    });

A principal coisa sobre isso é usando a propriedade exatamente o mesmo que o atributo do par de key-value JSON.

Eu tenho a seguinte chamada:

$('#select_box_id').change(function() {
        var action = $('#my_form').attr('action');
    $.get(action,{},function(response){
        $.each(response.result,function(i) {

            alert("key is: " + i + ", val is: " + response.result[i]);

        });
    }, 'json');
    });

A estrutura de voltar a partir do olhar do servidor como:

{"result":{"1":"waterskiing","2":"canoeing","18":"windsurfing"}}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top