jquery实现json数据解适于不同版本浏览器

来源:互联网 发布:kindle 知乎 编辑:程序博客网 时间:2024/04/30 11:58

                                                jquery的使用处理json传过来的值

在使用jquery来处理后台传递过来的json数据,下面这一种是最为基础的一种使用不同浏览器使用不同的xmlhttp对象来进行操作。当然这里也是用了动态添加元素到显示页面。

<script type="text/javascript">$(function(){//初始加载页面时运行loadXMLDoc();});var xmlhttp;function loadXMLDoc(){xmlhttp=null;if (window.XMLHttpRequest){// code for Firefox, Opera, IE7, etc.  xmlhttp=new XMLHttpRequest();  }else if (window.ActiveXObject){// code for IE6, IE5  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }if (xmlhttp!=null){  xmlhttp.onreadystatechange=state_Change;//调用对应的方法  xmlhttp.open("GET","<%=basePath%>/jsp/strutsJson.action",true);//这里是后台传递过来的 json数据地址,和调用的方法get  xmlhttp.send(null);  }else{  alert("Your browser does not support XMLHTTP.");  }}function state_Change(){if (xmlhttp.readyState==4)  {// 4 = "loaded"  if (xmlhttp.status==200)    {// 200 = "OK"    //document.getElementById('T1').innerHTML=xmlhttp.responseText;    //这里解析json数据    var jsonValue=xmlhttp.responseText;  var valueDo=eval("("+jsonValue+")");//alert(valueDo.userName);//alert(valueDo.arrayList.length);var txt1="<p>用户名:"+valueDo.userName+"</p>";  for(var i=0;i<valueDo.arrayList.length;i++)   {txt1+="<p>"+valueDo.arrayList[i].name+"</p>";} //var txt2=$("<p></p>").text("Text.");  // 以 jQuery 创建新元素//var txt3=document.createElement("p");//txt3.innerHTML="Text.";               // 通过 DOM 来创建文本$("#T1").append(txt1);        }  else    {    alert("Problem retrieving data:" + xmlhttp.statusText);    }  }}</script>  </head>   <body>  <div align="center">成功使用jquery来实现json数据的解析</div>  <div id="T1"></div>    </body>
用jquery的ajax来获取struts处理的json还尚未完成,待续。。。。。