2

嗨,我正在尝试使用 Ajax 从 servlet 返回一个简单的字符串,但没有返回任何内容,因为状态始终为 0,而 readystate 为 4。

这是.js代码

function validate(choice) {  
    //var url = "http://localhost:8080/examples/validate.do?id=" + escape(choice);                  
    var url = "../../validate.do" 
    if(window.XMLHttpRequest) {  
        req = new XMLHttpRequest();  
    }else if(window.ActiveXObject) { 
        req = new ActiveXObject("MSXML2.XMLHTTP.3.0"); 
    }  

    alert("IM IN VALIDATE() with " + choice); 
    req.open("GET", url, true);  
    req.onreadystatechange = callback;  
    req.send(null);   
    return false;

}  

function callback() { 
    if(req.readyState == 4 ) { 
        if(req.status == 200){ 
            var check = req.responseText;  
            alert(check);  
        }
        else
            alert(req.status);
    }  
}  

和Java代码

package model;  

import java.io.IOException;  
import java.io.PrintWriter;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;


public class DoAjaxServlet extends HttpServlet {  

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

            response.setContentType("text/html"); 
            response.setHeader("Access-Control-Allow-Origin", "*"); 
            response.setHeader("Cache-Control", "no-store");  
            response.setHeader("Pragma", "no-cache");  
            response.setDateHeader("Expires", 0);
            String resultStr = "JUST RETURNING THIS STRING";
            out.write(resultStr);
        } finally {   
            out.close();  
        }  
    }   

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

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

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

}  

我正在使用 Chrome 在 Tomcat 7 上运行它,并从 localhost:8080 访问 html 文件,而不是在本地运行,所以很多解决方案都无法正常工作。

即将

http://localhost:8080/examples/validate.do 

在 Chrome 中,它可以很好地打印字符串,所以我认为我没有写错 url。.js 文件位于类似

http://localhost:8080/examples/jsp/HTE/my.js

我还尝试在 .js 中直接使用“http://localhost:8080/examples/validate.do”作为 url 并将 setHeader("Access-Control-Allow-Origin", "*") 添加到 Java 文件但没有任何变化.

在帖子中搜索后,我正在对这个问题提出一些想法......你能告诉我这可能会出错吗?

4

0 回答 0