简体   繁体   中英

JavaScript ajax request to servlet call error callback function

I have the following code snippet:

$(d).ready(function() {
    $.ajax({
        url : "http://localhost:8080/ProjTest/TestServlet",
        type : "POST",
        dataType : "text",
        data : { test : "test" },
        error : function() {
            alert(1);
        },
        success : function(data) {
            alert(2);
        }
    });
});

and in my servlet:

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    Printer out = res.getWriter();
    String paramTest = req.getParameter("test");
    System.out.println("1");
    out.print(paramTest);
    out.close();
    System.out.println("2");
}

When I run, in console:

1
2

But, in javascript call error function !!!

Any idea ???


Solved:

I changed the servlet to

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setHeader("Access-Control-Allow-Origin", "*");
    Printer out = res.getWriter();
    String paramTest = req.getParameter("test");
    System.out.println("1");
    out.print(paramTest);
    out.close();
    System.out.println("2");
}

I added the line:

res.setHeader("Access-Control-Allow-Origin", "*");

There is no comma after the {} for data :

dataType : "text",
data : { test : "test" } 
// No comma here --------^
error : function() {

It should be like this:

dataType : "text",
data : { test : "test" },  // <--- can you see the comma :-D
error : function() {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM