stringify()在传递AJAX响应数据字段时意外返回undefined

时间:2015-07-10 16:34:23

标签: javascript jquery html

我正在拨打网络服务并使用JSON.stringify来获取查询的不同行,但当我尝试将其放入复选框时,会显示Nombre Jugador: undefinedCorreo[object HTMLInputElement]

我的代码:

function cargarJugadores2(){
    var req = $.ajax({
        url:'http://zz27.infoucrso.com/WSS/WSJugador.svc/cargarJugadores',
        timeout : 10000,
        dataType : "jsonp"
    });

    req.success(function(datos) {
        var nombre = JSON.stringify(datos.nombre);
        alert(nombre);
        ProcesarJugadores2(datos);
    });

    req.error(function(){
        alert("No fue posible establecer conexión con el Web Service");
    });
}

第二种方法:

function ProcesarJugadores2(datos) {
    var radiobutton = '<input type="radio" name="radio-choice-h-2" id="radio" onclick="escribir()"><label for="radio" id="label">' + 
        "</br>Nombre Jugador: " + this.nombre + " </br> Correo: "  + this.correo + '</label>'

    localStorage["correoSeleccionadoAmigo"] = this.correo;

    $('#listaJugadores').append(radiobutton);
    $('[type=radio]').checkboxradio().trigger('create');
    $('#listaJugadores').controlgroup().trigger('create');
}

这是返回的JSON的样子:

[{
    "Activo": true,
    "contrasenna": "1",
    "correo": "alex@gmail.com",
    "nombre": "Alex"
}, {
    "A‌​ctivo": true,
    "contrasenna": "1",
    "correo": "maria@gmail.com",
    "nombre": "Maria"
}, {
    "Acti‌​vo": true,
    "contrasenna": "1",
    "correo": "pedro@gmail.com",
    "nombre": "Pedro"
}]

2 个答案:

答案 0 :(得分:1)

你得到的

datos是一个对象数组。 nombre是数组中对象的属性。 为了获得一个特定值,首先获取数组值然后查看对象。所以你的代码应该是

var nombre = datos[index].nombre; //index will be array index.
alert(nombre); //no need to stringify nombre as you're doing array lookup.

或者,如果您直接存储JSON值,则将整个datos字符串化。

答案 1 :(得分:1)

这应该得到ProcesarJugadores2函数的正确输出:

function ProcesarJugadores2(datos) {
    var radiobutton = '<input type="radio" name="radio-choice-h-2" id="radio" onclick="escribir()"><label for="radio" id="label">' + 
        "</br>Nombre Jugador: " + datos.nombre + " </br> Correo: "  + datos.correo + '</label>'

    localStorage["correoSeleccionadoAmigo"] = datos.correo;

    $('#listaJugadores').append(radiobutton);
    $('[type=radio]').checkboxradio().trigger('create');
    $('#listaJugadores').controlgroup().trigger('create');
}

function cargarJugadores2(){
    var req = $.ajax({
        url:'http://zz27.infoucrso.com/WSS/WSJugador.svc/cargarJugadores',
        timeout : 10000,
        dataType : "jsonp"
    });

    req.success(function(datos) {
        datos.map(ProcesarJugadores2);
    });

    req.error(function(){
        alert("No fue posible establecer conexión con el Web Service");
    });
}

使用datos.map(),您可以对&#34;数据&#34;中的所有项目执行功能。阵列