JavaScript从服务器解析JSON

时间:2016-11-24 18:43:35

标签: javascript json

我正在尝试解析从我的服务器收到的JSON对象。这是我服务器的回复:

[
  {
    "idPais": "1",
    "nombre": "España"
  },
  {
    "idPais": "2",
    "nombre": "Grecia"
  },
  {
    "idPais": "3",
    "nombre": "Holanda"
  },
  {
    "idPais": "4",
    "nombre": "Finlandia"
  },
  {
    "idPais": "5",
    "nombre": "Suiza"
  }
]

在我的脚本中,我尝试使用一个数组获取对象,但resp始终为undefined

function loadCountries(cont) { // Listado de paises con contenidos
  var i = 0;
  var method = 'GET';
  var path = appConstants.requestCountriesURL(cont);
  console.log(path);
  var xhr = new XMLHttpRequest();   
  xhr.onreadystatechange = function() {
    alert('Status es: ' + xhr.status + 'State es: ' + xhr.readyState);
    if(xhr.readyState == 4 && xhr.status == 200) {
      alert('Recogiendo respuesta...');
      resp = xhr.responseText;
    }
  }
  xhr.open(method, path, false); // Creamos la peticion
  resp = xhr.send(); // Guardamos la respuesta
  if(resp == false || resp == undefined) {
    alert('La lista de paises no se pudo obtener');
    return resp;
  } else {
    alert('La lista de paises se obtuvo correctamente');
    console.log(resp);
    var listaPaises = JSON.parse(resp);
    return listaPaises;
  }
}

显示的错误如下:

Uncaught SyntaxError: Unexpected token u in JSON at position 0

使用解决方案1进行编辑

function checkCountries(i){
    alert('oncheckCountries');
    var answer=$('input[name^="radio-choice"]:checked').val();
    alert('val es: '+ answer);
    $('#divPaises').css('display','block');
    getCountries(answer);

}
function getCountries(continente){
    alert('on getCountries');
    loadCountries(continente);
}
function loadCountries(cont){ //Listado de paises con contenidos
    var i = 0;
    var method = 'GET';
    var path = appConstants.requestCountriesURL(cont);
    console.log (path);
    var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function(){
        alert('Status es: '+xhr.status+'State es: '+xhr.readyState);
        if(xhr.readyState == 4 && xhr.status == 200){
            alert('Recogiendo respuesta...');
            resp = xhr.responseText;
            if(resp == false || resp == undefined){
                alert('La lista de paises no se pudo obtener');
                return resp;
            }
            else{
                    alert('La lista de paises se obtuvo correctamente');
                    console.log(resp);
                    var listaPaises = JSON.parse(resp);
                    console.log(listaPaises[0]);
                    var size = Object.keys(listaPaises).length;
                    var select = document.createElement('select');
                    alert('Select creado');
                    select.name = 'selectPais';
                    select.id = 'selectPais';
                    for(i=0;i<size ;i++){
                            var option = document.createElement('option');
                            option.id = listaPaises[i].idPais;
                            option.value = listaPaises[i].nombre;
                            option.appendChild(document.createTextNode(listaPaises[i].nombre));
                            alert(option.getAttribute('value'));
                            select.appendChild(option);
                            }
                    document.getElementById('divPaises').appendChild(select);
                }
        }
    }
    xhr.open(method, path, true); //Creamos la peticion
    resp = xhr.send(); // Guardamos la respuesta    
}

2 个答案:

答案 0 :(得分:2)

您的问题是,您使用xhr.send()的结果作为回复,而不是。{如果您要解析响应,则必须使用onreadystatechangexhr.responseText侦听器中执行此操作,如下所示:

xhr.onreadystatechange = function(){
    alert('Status es: '+xhr.status+'State es: '+xhr.readyState);
    if(xhr.readyState == 4 && xhr.status == 200){
        alert('Recogiendo respuesta...');
        resp = xhr.responseText;

        if(resp == false || resp == undefined){
            alert('La lista de paises no se pudo obtener');
        } else {
            alert('La lista de paises se obtuvo correctamente');
            console.log(resp);
            var listaPaises = JSON.parse(resp);
        }
    }
}

此外,由于请求是异步的,因此您无法返回响应,因此您必须执行函数内部的所有操作,或使用回调函数,如下所示:

function loadCountries(cont, callback) { // use a callback
    var i = 0;
    var method = 'GET';
    var path = appConstants.requestCountriesURL(cont);
    console.log (path);
    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function(){
        alert('Status es: '+xhr.status+'State es: '+xhr.readyState);
        if(xhr.readyState == 4 && xhr.status == 200){
            alert('Recogiendo respuesta...');
            resp = xhr.responseText;

            if(resp == false || resp == undefined){
                alert('La lista de paises no se pudo obtener');
                callback(resp);
            } else {
                alert('La lista de paises se obtuvo correctamente');
                console.log(resp);
                var listaPaises = JSON.parse(resp);
                callback(listaPaises);
            }
        }
    }

    xhr.open(method, path, false);
    xhr.send();
}


// Create a callback
function myCallback(data) {
    // Do what you want with the data...
}

// Call the function like this...
function loadCountries(myCont, myCallback);

答案 1 :(得分:1)

这是一个异步调用,您尝试将其作为同步调用来处理。

  xhr.onreadystatechange = function() {
    alert('Status es: ' + xhr.status + 'State es: ' + xhr.readyState);
    if(xhr.readyState == 4 && xhr.status == 200) {
      alert('Recogiendo respuesta...');
      resp = xhr.responseText;
      //Do your stuff with resp here
    }
  }
  xhr.open(method, path, false); // Creamos la peticion
  xhr.send(); //Send will not return anything 

如果您需要更多示例,请点击此处:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest