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

用ajax怎么把数据返回成json格式?
请看我的代码:
HTML code
 var xmlHttp1;
    function createXmlHttp(){
        if(window.XMLHttpRequest){
            xmlHttp1=new XMLHttpRequest();
            
        }
        else{
                        xmlHttp1=new ActiveXObect("Microsoft.XMLHTTP");
                      }
    
    }
  
  function showJson(pageName){
        createXmlHttp();
        xmlHttp1.onreadystatechange=JsonCallBack;
        xmlHttp1.open("post",pageName,true);
        xmlHttp1.setRequestHeader( "Content-Type ",   "application/x-www-form-urlencoded "); 
        
        xmlHttp1.send(null);
        
        
    }
   function JsonCallBack(){
    
        if(xmlHttp1.readyState==4){
                if(xmlHttp1.status==200){
                alert(xmlHttp1.responseText);
                 var s='xmlHttp1.responseText';    //这里返回另一个jsp页面的数据
                 var optioninfo=eval('('+s+')');   [color=#FF0000]这里无法将返回的数据转化为json格式....[/color]
                                     var select=document.getElementById("test");
                 
                                     for(var o in optioninfo){
                                           select.appendChild(createOption(o,optioninfo[o]));
                                      }              
                [color=#FF0000]想把返回的数据依次加入到select中去,结果失败,alert(optioninfo.id)一下是undefined!这部分哪里错了?[/color]

                                                     
                      var user={'id':'2','name':'CSDN'};   [color=#FF0000]单独写个json[/color]
                   
                   
                    for(var o in user){
                    
                        select.appendChild(createOption(o,user[o]));
                        
                    }           [color=#FF0000]这样做就可以实现向下拉框中添加数据[/color]
                    
                }
            else{alert('请求操作返回数据未成功!');}
                
            }
            
        }
        
    
        
        function createOption(value,text){
            var opt=document.createElement("option");
            opt.setAttribute("value",value);
            opt.appendChild(document.createTextNode(text));
            return opt;
        
        }
    

另一个jsp页面:
HTML code
<body>
   <%
   StringBuffer buffer=new StringBuffer("{");
   buffer.append("'");
   buffer.append("id");
   buffer.append("':'");
   buffer.append("2");
   buffer.append("'");
   buffer.append(",");
   buffer.append("'");
   buffer.append("name");
   buffer.append("':'");
   buffer.append("CSDN");
   buffer.append("'");
   buffer.append("}");
   out.print(buffer.toString());
    %>
  </body>
</html>


请知道一下啊!

------解决方案--------------------
Jq有一个方法可以搞定、