Unable to pass JSONObject from JAVA Class to jsp
我已经看过这个例子,但是我仍然无法在JSP中检索JSON对象。以下是myCalendarController.java类中的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class MyCalendarController implements Controller{ public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { if("Add".equals(request.getParameter("action"))){ ... JSONObject jObj = new JSONObject(); jObj.put("test","Success"); response.getWriter().write(jObj.toString()); ... } return new ModelAndView("mycalendar","model", myModel); } |
下面是我试图在JSP中检索它的方法,但是警报总是说"未定义"。
1 2 3 4 5 6 7 8 9 10 11 | var queryString ="?action=Add"; queryString += "&t=" + title; queryString += "&sDT=" + stDate +"T" + stHour +":" + stMin +":00"; queryString += "&eDT=" + eDate +"T" + eHour +":" + eMin +":00"; $.ajax({ type:"GET", url:"mycalendar.htm" + queryString, success: function(response){ alert(response.test); } }); |
注意:当从JSP对类进行Ajax调用时,我正在尝试创建JSON对象。我不熟悉Ajax和Javascript,所以一定是做错了什么…请帮助!!!!
在上述代码中,response.responseText属性为"未定义"。但我尝试了另一种方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | var ajaxRequest; try{ ajaxRequest = new XMLHttpRequest(); }catch (e){ try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); }catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){ alert("Your browser broke!"); return false; } } } ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ alert(ajaxRequest.responseText); alert("test:" + ajaxRequest.test); } } var queryString ="?action=Add"; queryString += "&t=" + title; queryString += "&sDT=" + stDate +"T" + stHour +":" + stMin +":00"; queryString += "&eDT=" + eDate +"T" + eHour +":" + eMin +":00"; ajaxRequest.open("GET","mycalendar.htm" + queryString, true); ajaxRequest.send(null); |
这样我就得到了AjaxRequest.ResponseText,但是警报("test:"+AjaxRequest.test);仍然显示未定义
1 2 3 4 5 6 7 | var a = '<%=DropDown.returnList()%>'; var countryObj = JSON.parse(a); var s = $('#selectCountry'); for(var val in countryObj) { $('<option />', {value: val, text: countryObj[val]}).appendTo(s); } |
我不太确定,你可以试一下。