【问题标题】:Call ajax to servlet call always the error function调用 ajax 到 servlet 调用总是错误函数
【发布时间】:2017-03-27 22:00:08
【问题描述】:

我正在尝试使用 ajax 和 servlet 进行一些测试,但是当我启动应用程序时,servlet 总是返回“错误”

package servlet;

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


@WebServlet(name = "ServletCatalogue", urlPatterns = "/test")
public class ServletCatalogue extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.write("test");
    }
}
$(function() {
    $("#catalogue").on('click', function() {
        $.ajax({
            url: "/test",
            type: "GET",
            success: ok,
            error: error
        });
    });
});

function ok() {
    alert("fine")
};

function error() {
    alert('error')
}

为什么总是打印"error"?我知道 JS 正确调用了 servlet,因为我放了一个 system.out 来检查它。

【问题讨论】:

  • 它运行错误处理程序,因为请求没有返回 2xx HTTP 响应代码。您需要诊断为什么会这样。
  • 在浏览器中打开 /test 并粘贴页面中的错误
  • 尝试将状态参数添加到错误事件处理方法中,看看是什么原因导致错误,可能是您的服务器不可访问。
  • 尝试通过out.flush();提交响应。看看您是否将响应返回到浏览器级别。
  • @Sagar 如果我去 \test 它打印'test'

标签: javascript java jquery ajax servlets


【解决方案1】:

我正在使用 Java Servlet 接收呼叫。首先搞清楚是什么原因。我使用以下功能做到了这一点

function ajaxFailure(data, textStatus, errorThrown){
                alert("OH NO! data: "+data + ' textStatus: ' + textStatus + 'errorThrown: ' + errorThrown);
             }

我发现错误是由于 errorThrown: No conversion from text to application/json 然后我在 $.ajax 调用中将 application/json 更改为 text。这解决了我的问题

【讨论】:

    猜你喜欢
    • 2018-02-09
    • 2013-10-03
    • 2013-12-11
    • 2015-11-12
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    相关资源
    最近更新 更多