跨域请求-JSONP

2019-10-12  本文已影响0人  毛不翼

前端

(function ($) {
    $.loginCheck = function (pram1, pram2, success, error) {
        let URL_DOMAIN = "//xxx.fireface.cn/xxx/xx/xx?";
        let url = URL_DOMAIN + "pram1=" + pram1+ "&pram2=" + pram2;
        call(url,success,error)

    };
    $.getAuth = function (success, error) {
        let AUTH_URL = "//xxx.fireface.cn/xxx/xx/xx?";
        call(AUTH_URL,success, error);
    };
    let call = function (url, success, error) {
        url += url.indexOf("?") > 1 ? "&callback=callback" : "?callback=callback";
        let brake = false;
        let head = document.getElementsByTagName('head')[0];
        let script = document.createElement('script');
        head.appendChild(script);

        window.callback = function (data) {
            if (brake) {
                return false;
            }
            brake = true;
            head.removeChild(script);
            clearTimeout(script.timer);
            success && success(data);
        };

        script.src = url;
        script.timer = setTimeout(function () {
            if (brake) {
                return false;
            }
            brake = true;
            head.removeChild(script);
            error && error({
                message: '超时'
            });
        }, 10000);
    };
})(LoginCaller = {});

function successCallback(responseText){
    //兼容转换为对象,浏览器差异,可是是json串或者是object类型
    var data= typeof responseText == 'string' ? JSON.parse(responseText) : responseText;
    console.log(data.success);
    console.log(data.code);
}
function errorCallback(responseText){
    //兼容转换为对象,浏览器差异,可是是json串或者是object类型
    var data = typeof responseText == 'string' ? JSON.parse(responseText) : responseText;
    console.log(data.message);
    console.log(data.code);
}
 
LoginCaller.getAuth(successCallback,errorCallback);

后端

 public String XXX() {
        try {
            String pram1= request.getParameter("pram1");
            String pram2= request.getParameter("pram2");
            String callback = request.getParameter("callback");

            Map<String, Object> resultMap = new HashMap<>();
            if (pram1 != null) {
                if (pram1.equalsIgnoreCase(pram1)) {
                    setCookie(response, "pram1", pram1);
                    resultMap.put(SUCCESS, "true");
                } else {
                    resultMap.put(SUCCESS, "false");
                }

            }
            PrintWriter writer = response.getWriter();
            writer.append(callback).append("(").append(JSON.toJSONString(resultMap)).append(")");
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
上一篇下一篇

猜你喜欢

热点阅读