第一种(jsonp):http://www.cnblogs.com/Garnett-Boy/p/6222870.html
第二种:(CORS):只需要在服务器端返回查询结果时添加,这样只需要修改后台服务代码就可以实现浏览器的跨域请求了。
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET,POST");
代码:
package com.sxdx.employee.action; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSON; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.sxdx.employee.dao.employeeDao; import com.sxdx.employee.domain.employee; import com.sxdx.employee.service.employeeImpl; @Controller @RequestMapping(value="/employeeAction") public class employeeAction { @RequestMapping(value="/showEmployeeList.do") public String showEmployeeList(HttpServletRequest request,HttpServletResponse response){ JSONObject jsonboject=new JSONObject(); JSONArray rows = new JSONArray(); System.out.println(request.getParameter("pageNumber")); System.out.println(request.getParameter("pageSize")); employeeDao empDao=new employeeImpl(); System.out.println(empDao.selectAll()); for(employee emp:empDao.selectAll()){ JSONObject cell = new JSONObject(); cell.put("eid", emp.getEid()); cell.put("ename", emp.getEname()); cell.put("esex", emp.getEsex()); cell.put("eage", emp.getEage()); rows.add(cell); } jsonboject.put("rows", rows); jsonboject.put("total", empDao.selectAll().size()); PrintWriter out = null; try { response.setCharacterEncoding("UTF-8"); //设置编码格式 //response.setContentType("text/html"); //设置数据格式 String act = request.getParameter("act");//是否跨域请求,在请求时通过参数传递,以便后面判断是否需要按照跨域请求做返回 out = response.getWriter(); if(act.equals("area")){//如果是跨域请求执行此分支 response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "GET,POST"); //String callback=request.getParameter("callback");//此处即为跨域请求核心操作,回调方法 //out.write(callback+"('"+rows.toString()+"')"); out.write(rows.toString()); }else{ out.write(rows.toString()); } out.flush(); } catch (IOException e) { e.printStackTrace(); } finally{ out.close(); } return null; } }