我目前有一个网页,该网页使用执行以下操作的JavaScript:

function callSomething(parm) {
    req = false;
    if (window.XMLHttpRequest) {
        try {
            req = new XMLHttpRequest();
        } catch (e) {
            req = false;
        }
    } else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                req = false;
            }
        }
    }

    if (req) {
        var url_str = "/Servlet?parm=" + parm;
        req.open("GET", url_str, false);
        req.onreadystatechange = processReqChange;
        req.send(null);
        // process the response
    }
    return something;
}


我担心的是,如果有人在浏览器窗口中手动输入完整的URL(例如“ http://somesampleserver.com/Servlet?parm=something”),也会显示响应。如何防止这种情况发生?我只希望代码能够获得响应。

最佳答案

听起来您想检查这是否是XHR请求。您可以检查X-Requested-With标头

Boolean isXHR = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));


关于here的更多信息

10-07 20:40