簡體   English   中英

JavaScript從服務器解析JSON

[英]JavaScript parsing JSON from server

我試圖解析從我的服務器收到的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    
}

你的問題是你使用xhr.send()的結果作為響應,而不是。 如果要解析響應,則必須使用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);
        }
    }
}

此外,您無法返回響應,因為請求是異步的,因此您必須執行函數內部的所有操作,或使用回調函數,如下所示:

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

這是一個異步調用,您嘗試將其作為同步調用。

  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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM