日期:2014-05-16  浏览次数:20694 次

json格式返回值页面显示undefined - Web 开发 / Ajax
HTML code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <script type="text/javascript">

 function createXHR()
 {
 var request = false;
 try
 {
 request = new ActiveXObject('Msxml2.XMLHTTP');
 }
 catch (err2)
 {
 try
 {
 request = new ActiveXObject('Microsoft.XMLHTTP');
 }
 catch (err3)
 {
 try
 {
 request = new XMLHttpRequest();
 }
 catch (err1)
 {
 request = false;
 }
 }
 }
 return request;
 }

 function loadJSON(fname)
 {
 var xhr = createXHR();
 xhr.open("GET", fname, true);
 xhr.onreadystatechange = function()
 {
 if (xhr.readyState == 4)
 {
 if (xhr.status != 404)
 {
[color=#FF0000]var data = eval("(" + xhr.responseText + ")");       //到这时还有值
 document.getElementById("zone").innerHTML = "<h2>Items:</h2>";//再走就变成undefined[/color]
 for (i = 0; i < 3; i++)
 {
 document.getElementById("zone").innerHTML += data.listing.items[i].description + ', price <i>' + data.listing.items[i].price + "</i><br/>";
 }
 }
 else
 {
 document.getElementById("zone").innerHTML = fname + " not found";
 }
 }
 }
 xhr.send(null);
 }


 </script>
 <title>Ajax Get JSON Demo</title></head>


<body bgcolor="#FFFFFF">

<p><font size="+3">Ajax JSON/JAXB Demo</font></p>
<hr>
<FORM name="ajax" method="POST" action="">

 <p>
 <INPUT type="BUTTON" value=" Click to load the JSON file " ONCLICK="loadJSON('resteasy/tutorial/items')">
 </p>

</FORM>


<div id="zone"></div>

</body>
</html>    

模拟数据传值到页面能显示,从数据库中查到的数据在页面上显示为undefined

------解决方案--------------------
var data = eval("{" + xhr.responseText + "}");
------解决方案--------------------
var data = eval("(" + xhr.responseText + ")"); //到这时还有值
干嘛这么操作呢.
var data = xhr.responseText; 不就好了么.

------解决方案--------------------
zone
这个 东东 有么?没看到哪里说你的JSON数据是undefined的啊.

------解决方案--------------------
探讨

其实后台传值过来都是json形式的字符串即{"name":"value"}的形式,在js中它并不是json对象,而是字符串。所以要通过eval函数才能把换回的变成json对象,这样你就可以获得换回的json对象的信息了