javaweb中ajax跨域访问实例

 $.ajax({
    url:"http://192.168.6.21:8080/jsonp/servlet/Ajax",
   data:"data=guoyansi",
   type:"get",

   dataType:"jsonp",

  jsonp:"callbackparam",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的接受 的参数名(默认为callback)

   jsonpCallback:"jsonpCallback",// 可选项,写上表示返回函数的函数名用“ jsonpCallback”,不写 默认为jQuery自动生成的随机函数,
   error:function(){alert("服务器连接失败");},
   success:function(data){
   for(var key in data){
    alert(key+":"+data[key]);
   }
  }

 });

 import net.sf.json.JSONArray;
 import net.sf.json.JSONObject;

public class Ajax extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    response.setContentType("text/plain");
    response.setCharacterEncoding("utf-8");
    String callbackparam=request.getParameter("callbackparam");
    System.out.println("callbackparam:"+callbackparam);
    String name=request.getParameter("data");
    System.out.println("param:"+name);
    Map<String, String> map=new HashMap<String, String>();
    map.put("1", "a");
    map.put("2", "b");
    map.put("3", "c");
    map.put("4", "d");
    JSONObject jsonObject=JSONObject.fromObject(map);
    String result=jsonObject.toString();
    PrintWriter writer=response.getWriter();

//如果ajax请求写了 jsonpCallback:"jsonpCallback",
    writer.write("jsonpCallback("+result+")");

//如果ajax请求没有写 jsonpCallback:"jsonpCallback",

    writer.write(callbackparam+"("+result+")");//需要callbackparam参数接收随机函数名

}

}



你可能感兴趣的:(javaweb中ajax跨域访问实例)