Jquery-Ajax + Java服务器跨域问题解决

如何快速解决

最近没有时间完善细节问题,先在此记录一下问题的解决方案,后期有时间了再补充细节性问题。

问题:

XMLHttpRequest cannot load http://localhost:8082/serves/SaveTitleInfo. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

或者:Uncaught SyntaxError: Unexpected token

直接上代码,不知道怎么改代码的同志们可以直接复制粘贴,代码能跑起来了再研究怎么融合到自己的代码中。

  • Jquery :
$.ajax({
    url : '请求的地址',
    type : "POST",
    dataType : 'jsonp',
    jsonp : "callback",
    jsonpCallback : "suc",
    data : "",
    success : function(result) {
        alert(result.result);
    }
});
  • Java服务器:

PrintWriter writer = response.getWriter();

StringBuilder sb = new StringBuilder("");
String titleId = request.getParameter("title_id");
sb.append("if you see this, it means successful.");

try {
    JSONObject json = new JSONObject();
    json.put("result", sb.toString());
    sb = new StringBuilder(json.toString());
} catch (JSONException e) {
    sb = new StringBuilder("{\"result\" : \"错误\"}");
}

String callback = request.getParameter("callback");
if (callback != null) {
    writer.append(callback).append("(").append(sb.toString());
    writer.append(")");
} else {
    writer.append(sb.toString());
}

猜你喜欢

转载自blog.csdn.net/qq_36639912/article/details/82381425