简体   繁体   English

JavaScript从服务器解析JSON

[英]JavaScript parsing JSON from server

I am trying to parse a JSON object received from my server. 我试图解析从我的服务器收到的JSON对象。 This is my server's response: 这是我服务器的回复:

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

In my script, I tried to get the objects with one array, but resp is always undefined . 在我的脚本中,我试图用一个数组获取对象,但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;
  }
}

The error shown is the following: 显示的错误如下:

Uncaught SyntaxError: Unexpected token u in JSON at position 0

Edit with solution 1: 使用解决方案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    
}

Your issue here is that you are using the result of xhr.send() as the response, when it's not. 你的问题是你使用xhr.send()的结果作为响应,而不是。 If you want to parse the response you have to do it in the onreadystatechange listener, using xhr.responseText , like this: 如果要解析响应,则必须使用xhr.responseTextonreadystatechange侦听器中xhr.responseTextxhr.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);
        }
    }
}

Also, you cannot return the response since that the request is asynchronous, so you have to either do everything inside your function, or use a callback function, like this: 此外,您无法返回响应,因为请求是异步的,因此您必须执行函数内部的所有操作,或使用回调函数,如下所示:

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);

It is an asynchronous call and you are trying to handle it as a synchronous one. 这是一个异步调用,您尝试将其作为同步调用。

  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 

Check here if you want more examples: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest 如果您需要更多示例,请在此处查看: https//developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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