51前写的一篇跨域提交数据的blog——JQuery AJAX跨域提交参数、接收json数据,在IE中使用时,页面会弹出提示“该页正在访问其控制范围之外的信息。这可能导致安全风险。是否继续?”,虽然在chrome和firefox里面则没这个提示,但IE用户还是较多,总感觉有点用户体验上有所欠缺,今天参考IBM社区的一篇文章——使用 JSONP 实现跨域通信,改了一下代码,使用jsonp的方式来实现,修改如下:
Servlet代码:
public class ProvideCourseInfo extends HttpServlet{ private static final long serialVersionUID = -487357559770822253L; private ICourseService courseService; @Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException { String jsonData = getDataAsJson(req.getParameter("symbol")); String output = req.getParameter("callback") + "(" + jsonData + ");"; resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/javascript"); PrintWriter out = resp.getWriter(); out.println(output); } private String getDataAsJson(String courseNumber) { if(StringUtil.isBlank(courseNumber)){ Course course = courseService.getValidCourse(courseNumber); if(course!=null){ StringBuilder sb = new StringBuilder(); String courseName = course.getCourseName(); sb.append("{"); sb.append("\""); sb.append("courseName"); sb.append("\""); sb.append(":"); sb.append("\""); sb.append(courseName); sb.append("\""); Integer lang = course.getLang(); sb.append(","); sb.append("\""); sb.append("lang"); sb.append("\""); sb.append(":"); sb.append("\""); sb.append(lang); sb.append("\""); sb.append("}"); course = null; return sb.toString(); } } return "0"; } @Override protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { this.doGet(request,response); } @Override public void init() throws ServletException { super.init(); ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this .getServletContext()); courseService = (ICourseService) context.getBean("courseService"); } }
jsp代码:
<script type="text/javascript"> function showCourseInfo(){ var resourceCode = document.getElementById("resourceCode").value; jQuery.getJSON("http://10.10.6.31:8099/jsonp/provideCourseInfo?symbol="+resourceCode+"&callback=?",function(data) { if(data!="0"){ document.getElementById('resourceName').value = data.courseName; document.getElementById('languageType').value = data.lang; }else{ document.getElementById('resourceName').value = ''; document.getElementById('languageType').value = ''; alert("课件编码不存在!!!"); } }); } </script> <dt> <label><span>*</span> 课件编码:</label> </dt> <dd> <input type="text" class="default_txt" id="resourceCode" name="resourceCode" value="112290_eng"/> <input name="Button2" type="button" class="btn btn_default" onclick="showCourseInfo()" value="Load…" /> </dd>