2016-11-24 18 views
1

私のサーバーから受け取ったJSONオブジェクトを解析しようとしています。これは私のサーバーの応答です:私のスクリプトでサーバーからJSONを解析するJavaScript

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

、私は1つのアレイでオブジェクトを取得しようとしたが、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; 
    } 
} 

示すエラーは以下の通りです:ソリューション1と

Uncaught SyntaxError: Unexpected token u in JSON at position 0 

編集:

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  
} 
+0

可能な重複http://stackoverflow.com/questions/14220321/how- do-i-return-from-as-asynchronous-call) – JJJ

+1

レスポンスを返した後に 'resp'をチェックしてはいけませんか?今すぐサーバーが応答を返す前にそれをチェックしています。 –

+0

は完全にその投稿と重複しません。 – Asier

答えて

2

ここにあなたの問題は、応答としてxhr.send()の結果を使用していることです、そうでないときは。あなたはこのように、xhr.responseTextを使用して、onreadystatechangeリスナーにそれをしなければならない応答解析する場合:また

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

お返事ありがとうございます。この場合、私の要求は同期的で、なぜ私は値を "返す"ことができないのですか? – Asier

+0

@Asierいいえ、あなたのリクエストは非同期です! xhr.open()の最後のパラメータでfalseを使用しているため、非同期です。 –

+0

私はそうではないと思います、真実は非同期です、偽は同期です。 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests – Asier

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

[?私は非同期呼び出しからの応答を返すにはどうすればよい](の
+0

答えをありがとう。その正しいが、私は最初に別のものを読んだ。ありがとうございました! – Asier

関連する問題