调用servlet时Ajax状态为0

时间:2013-01-17 04:06:54

标签: ajax servlets tomcat7

您好我正在尝试使用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中它打印字符串就好了,所以我想我没有写错误的网址。 .js文件位于

之类的位置
http://localhost:8080/examples/jsp/HTE/my.js

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

在帖子中搜索后,我正在运行这个想法...你能告诉我这可能出错的地方吗?

0 个答案:

没有答案