Ajax错误函数没有在java

时间:2016-11-15 11:55:26

标签: javascript java jquery ajax jsp

Ajax错误函数未在java中调用

这是ajax方法: -

$.ajax({
    type:"post",
    timeout:5000,
    url:"<s:property value="URL"/>",
    data:{name:newName},
    success:function () {
        $("#errorDiv").html("Successfully updated");
    },
    error:function (data) {
        $("#errorDiv").html("Error.");
    }
})

更新用户方法: -

    @Action(value = "renameUser", results = {@Result(name = "success", type = "json"),
    @Result(name = "input", type = "tiles", location = "view.list")},
            interceptorRefs = {@InterceptorRef("auditingAdminDefault")})
    @Override
    public String execute() throws Exception {
        String result = "input";
        try {
            updateUser(name);
            addActionMessage(name + " user name was successfully updated.");
            result = "success";
        } catch (Exception e) {
            addActionMessage(e.getMessage());
            result = "input";
        }
        return result;
    }
}

updateUser();

updateUser() throws Exception {

if (..) {

} else {
  throw Exception();
}

我能够成功更新用户而不会出现问题。但是成功更新或任何错误都会调用成功函数。

我需要在Ajax中使用两件事。

  • 应根据结果调用成功和错误方法
  • 我需要从更新用户方法中捕获错误并在UI中显示它。

请有人告诉我这里我做错了什么?

2 个答案:

答案 0 :(得分:1)

您正在捕获操作方法中的所有错误并向客户端返回有效响应。

catch (Exception e) {
        addActionMessage(e.getMessage());
        result = "input";
    }

return result;

这就是为什么即使在失败的情况下,也会调用成功回调,因为对于客户端,响应是有效的。如果发生异常,你应该在action方法中返回一个错误。

理想情况下,您应该为任何异常返回错误视图。

catch (Exception ex)
{
   addActionMessage(e.getMessage());
   return View("Error");
}

但是在你的情况下你想在同一个视图中显示错误,因此你可以做类似的事情

你可以做异常的事情。

public ActionResult execute() throws Exception {
{
    try
    {
        //code everything works fine
    }
    catch (Exception ex)
    {
         return new HttpStatusCodeResult(500);
    }
}

答案 1 :(得分:0)

我能够解决以下问题: -

  1. 发生错误时未调用Ajax错误回调
  2. 从方法中捕获异常并在ajax函数中显示
  3. 以下是更新后的方法及其现在的工作方式: -

    更新用户方法: -

    private String errorStatement;
    
    public String getErrorStatement() {
        return errorStatement;
    }
    
    @Action(value = "renameUser", results = {@Result(name = "success", type = "json"),
    @Result(name = "input", type = "json", , params = { "statusCode", "500" })},
            interceptorRefs = {@InterceptorRef("auditingAdminDefault")})
    @Override
    public String execute() throws Exception {
    
        try {
            updateUser(name);
    
            return SUCCESS;
        } catch (Exception e) {
            errorStatement = e.getMessage();
            return ERROR;
        }
    
    }
    

    }