Ajax跨域访问,访问成功但一直走error不走success的的问题解决
通过搜索各种资料,终于解决啦,废话不多说了,还是老规矩直接上代码: 我这里用了jsonp,有想了解的点击 : jsonp 前端代码: - $.ajax({
- type:'post',
- url:'http://171125dv96.iask.in/weiqing_manage/Package.json',
- dataType:'jsonp',
- jsonp:'callback',
- data:{phone:18865920808, type:'0'},
- jsonpCallback:"successCallback",
- success:function(data){
- alert("成功!success");
- alert(data.name);
- },
- error:function(XMLHttpRequest, textStatus, errorThrown){
- alert("失败!error");
- alert(XMLHttpRequest.status);
- alert(XMLHttpRequest.readyState);
- alert(textStatus);
- }
- });
- /*
- *回调名successCallback可以自定义,必须和后台响应的名
- *对应
- *
- *如果XMLHttpRequest.status打印值为200
- *XMLHttpRequest.readyState为4
- *textStatus为parsererror
- *
- *parsererror:解析错误
- *由parsererror可以看出应该就是后台返回的数据格式有问题
- *了
- */
复制代码后台代码:
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/json;charset=UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- String TELPHONE = request.getParameter("phone");
- String TYPE = request.getParameter("type");
- System.out.println("------------------------------------------");
- System.out.println("telphone: " + TELPHONE);
- System.out.println("type: " + TYPE);
- try {
- Package p = new Package();
- Gson gson = new Gson();
- String st = " 手机号:"+TELPHONE+",type:"+TYPE;
- System.out.println("111111111111111111111");
- p.setName(st);
- System.out.println(" 测试: " + gson.toJson(p));
- out.print("successCallback(" + gson.toJson(p) + ")");//尤其注意这里返回的数据格式: {"name":" 手机号:18865920808,type:0"}
- /*
- *因为Jsonp的返回类型:回调函数名+(+json+)
- *
- */
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- out.flush();
- out.close();
- }
- }
复制代码后台打印:
|