我无法使用 AJAX 从 servlet 检索responseText

Sea*_*ock 1 javascript java ajax servlets

我有一个名为 的 servlet 文件NewServlet.java。我的 AJAX 脚本调用此 servlet 来检索响应。

我已经通过在浏览器中测试 servlet 来验证它。

但是当我从我的 AJAX 脚本中调用它时,它给了我一个空白responseText和一个错误,上面写着

XMLHttpRequest 无法加载 http://localhost:8084/WebApplication1/NewServlet。Access-Control-Allow-Origin 不允许 Origin null

NewServlet.java

import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class NewServlet extends HttpServlet {


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();


        out.println("<option value='1'>one</option>");
        out.println("<option value='2'>two</option>");
        out.println("<option value='3'>three</option>");
        out.println("<option value='4'>four</option>");
        out.println("<option value='5'>five</option>");
        out.close();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }


    public String getServletInfo() {
        return "Short description";
    }

}
Run Code Online (Sandbox Code Playgroud)

测试.html

<html>

<head>
    <script language = "javascript">
        var xmlDoc = 0;
        var xhttp = 0;
        function reciveData()
        {

            if (window.XMLHttpRequest)
            {
                xhttp=new XMLHttpRequest();
            }
            else // IE 5/6
            {
                xhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xhttp.onreadystatechange = redirectUser;        
            xhttp.open("GET","http://localhost:8084/WebApplication1/NewServlet",true);
            xhttp.send();
            }

        function redirectUser()
        {
            if (xhttp.readyState == 4)
            {
                log = 0;
                xmlDoc = xhttp.responseText;
                alert(xmlDoc);
            }
        }
    </script>
</head>
<body onload="reciveData()">

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

有人能给我指出正确的方向吗?

谢谢。

ste*_*vls 5

这是在浏览器端......安全模型只允许 AJAX 请求到您从中获取页面的同一主机/端口。确保您已通过服务器获取页面(例如http://localhost:8084/test.html),而不是通过文件系统加载它。那么你应该可以开始了……或者至少继续调试。;)