JavaScript解析来自服务器的JSON
问题描述:
我想解析从我的服务器收到的JSON对象。这是我的服务器的响应:JavaScript解析来自服务器的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()
结果作为响应,当它不是。如果要分析你所要做的是在onreadystatechange
听众的响应,使用xhr.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
+0
感谢您的回答。它的正确,但我先读了另一个。谢谢! – Asier
的[?我如何返回从一个异步调用的响应(可能的复制http://stackoverflow.com/questions/14220321/how- do-i-return-from-an-asynchronous-call) – JJJ
你不应该在得到回应后检查'resp'吗?现在,您甚至在服务器向您发送回复之前检查它。 –
完全没有重复该帖子。 – Asier