jquery ajax 跨域请求【原】

前台

function sending(){
    $.ajax({
        
        type : "get",//jsonp只能get
        async:true,
        url : "/webcontext/jsonptest.do",//##test1
        dataType : "jsonp",
        data:{"name":"bobo","age":"18"},
        jsonp: "callback",//服务端用于接收callback调用的function名的参数
        jsonpCallback:"jsonpCallback",//callback的function名称
        beforeSend: function () {
            
        },
        success : function(json){
            $("#result").text(json.respInfo);
        },
        complete: function () {
            
        },
        error: function (data) {
            console.info("error: " + data.responseText);
            return;
        }
    });
}

后台

只要后台能返回前台指定的jsonpCallback回调名并加一些()即可实现跨域.如当前样例返回:

jsonpCallback({"errorCode":"0000","respInfo":"task is run..."})

也就是在原来json报文的基础上额外添加 回调名(json)

public void doPost(HttpServletRequest request, HttpServletResponse response) {
    PrintWriter pw = null;
    String jsonpCallback = request.getParameter("callback");
    String result = jsonpCallback + "(" + "{\"errorCode\":\"0000\",\"respInfo\":\"task is run...\"}" + ")";
    pw.write(result);
    pw.flush();
    pw.close();
}

其它参考

[转] 由Request Method:OPTIONS初窥CORS==>https://www.cnblogs.com/chris-oil/p/8042677.html