Return JSON from a JSP

I need using a JSP returns JSON, so wrote the following codes for testing. Fortunately it works.

/*
 This file name is json.jsp. It posts itself, then get JSON.
*/
<%response.setHeader("Cache-Control", "no-cache");%>
<%response.setHeader("Pragma", "no-cache");%>
<%
String t = request.getParameter("t");
if(t==null){
%>
<!DOCTYPE html>
<% response.setHeader("contentType","text/html;charset=UTF-8");
%>
<script type="text/javascript">
  var XHR;
  function requestJSON(){
      if ( window.XMLHttpRequest )
         XHR = new XMLHttpRequest();
      else if ( window.ActiveXObject ) {
         try {
            XHR = new ActiveXObject('Msxml2.XMLHTTP');
         }
         catch(err) {
            XHR = new ActiveXObject('Microsoft.XMLHTTP');
         }
      }
      XHR.open( "POST", "json.jsp", true );
      XHR.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded');
     // alert("inside content loader send request");
      XHR.onreadystatechange = function() { getJSON() };
      //alert("inside content loader send request after response");
      var pStr="t=1";
      var sIdSV = document.getElementById("idSV").value;
      if(sIdSV!=undefined&&sIdSV!=null&&sIdSV.trim()!=""){pStr=pStr+sIdSV}else{pStr=null;}
      XHR.send( pStr );     
  }
   function getJSON(){
        var s = document.getElementById("test1").innerHTML;
        var s1=XHR.readyState;
        s1=s1+" "+XHR.status
        if(XHR.readyState==4  && XHR.status==200){
          s1=s1+XHR.responseText;
          var a = JSON.parse(XHR.responseText);
          s1=s1+"<h3>test:"+a.test+"</h3>";
        }
        s=s1+"<br/>"+s;
        document.getElementById("test1").innerHTML=s;
      }
    </script>
    </head>
    <body>
    <input type="text" id="idSV" value="Get JSON"></input>
    <input type="button" onclick="requestJSON();" value="Get JSON"></input>
    <p id="test1"></p>
    </body>
</html>
<%
}else{
response.setHeader("contentType","application/json; charset=UTF-8");
%>
<%="{\"test\":\"I'm from server! You sent to me "+t+" ?\"}" %>

<%}%>
a screenshot:



评论

此博客中的热门博文

XML, XSL, HTML

Input in element.eleme.io

Data URI是由RFC 2397 ACE