struts2 Ajax错误结果

发布于 2024-12-11 16:57:31 字数 1252 浏览 0 评论 0原文

我在struts.xml中有这个配置

<action name="updateAction"
    class="it.myApp.action.ajax.UpdateActionAction">
<result name="success" type="json"/>
<result name="error" type="json"/>
</action>

,这是我的Action类

...
try{
    act.update();
}catch(Exception e){
    Logger.print(MessageType.ERROR,"Update failed "+e.getMessage());
    return ForwardResult.ERROR;
}
return ForwardResult.SUCCESS;

最后,这是jQuery ajax函数,

$.ajax({
    url: 'updateAction.action',
    traditional:true,
    data : {
        'actionId': id,
        'actionName': name,
        'actionDescr':descr
    },
    success: function(data) {
        $('#act_'+id).html(data.name);
        $('#des_'+id).html(data.descr);
        $('#update_'+id).html(data.update);
        $('#userId_'+id).html(data.userId);

        $('#mdf_'+id).css("display","block");
        $('#save_'+id).css("display","none");   
        $('#diag_'+id).html(data.result);
    },
    error: function(data){
        alert("AZZ!");
        $('#diag_'+id).html(data.result);
    }
}); 

当action成功更新数据时,没有问题,ajax函数执行“成功”语句,但是当action抛出异常时,ajax不执行“错误”语句,而是再次“成功”......

为什么?

提前谢谢

M。

I have this configuration in struts.xml

<action name="updateAction"
    class="it.myApp.action.ajax.UpdateActionAction">
<result name="success" type="json"/>
<result name="error" type="json"/>
</action>

this is my Action class

...
try{
    act.update();
}catch(Exception e){
    Logger.print(MessageType.ERROR,"Update failed "+e.getMessage());
    return ForwardResult.ERROR;
}
return ForwardResult.SUCCESS;

at last, this is jQuery ajax function

$.ajax({
    url: 'updateAction.action',
    traditional:true,
    data : {
        'actionId': id,
        'actionName': name,
        'actionDescr':descr
    },
    success: function(data) {
        $('#act_'+id).html(data.name);
        $('#des_'+id).html(data.descr);
        $('#update_'+id).html(data.update);
        $('#userId_'+id).html(data.userId);

        $('#mdf_'+id).css("display","block");
        $('#save_'+id).css("display","none");   
        $('#diag_'+id).html(data.result);
    },
    error: function(data){
        alert("AZZ!");
        $('#diag_'+id).html(data.result);
    }
}); 

when action updates data with success, there aren't problems, ajax function executes "success" statement, but when action throws an exception, ajax doesn't execute "error" statement but "success" again...

why?

thanks advance

M.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

魂ガ小子 2024-12-18 16:57:31

因为请求没有生成错误,其中“error”表示服务器返回 HTTP 错误代码。服务器响应可以以不同方式指示错误,例如错误属性。

您可以使用 Firebug 或类似的工具检查响应代码和内容;如果您期望返回的内容不是它返回的内容,请在问题中添加一些详细信息,说明它返回的内容以及您希望看到的内容。

最简单的选项是设置结果的 statusCodeerrorCode,详细信息请参阅 JSON 插件文档。 (假设这是您正在使用的 JSON 插件。)

Because the request didn't generate an error, where "error" means the server returns an HTTP error code. The server response may indicate an error in a different way, e.g., an error property.

You can check the response code and contents using Firebug or something similar; if you're expecting something other than what it sends back, add some details to the question stating what it returns, and what you'd like to see instead.

The easiest option is to set the statusCode or errorCode of the result as detailed in the JSON plugin docs. (Assuming that's the JSON plugin you're using.)

耳根太软 2024-12-18 16:57:31

Hello Ging3r

通常,JSP 网站需要 JSON 插件来编码/解码 JSON 消息。

JSON.simple 是 JSON 插件的一个很好的示例。 JSON.simple 网站 还提供了在 JSP 网站上设置 JSON 的教程。

如果您更喜欢使用特定于 Struts 的插件,Apache 网站上有几个 适用于 Struts2 的 JSON 插件< /a>.

编辑

我绝对不是 JSP 方面的专家,并且对您正在使用的 JSON Struts 插件一无所知,尽管我对 json-simple.

尽管如此,以下两个例子对我来说还是有意义的。这些示例来自上面提到的教程。

示例 1 - 服务器端 JSP 编码

service.jsp: 
  <%@page contentType="text/html; charset=UTF-8"%>
  <%@page import="org.json.simple.JSONObject"%>
  <%
    JSONObject obj=new JSONObject();
    obj.put("name","foo");
    obj.put("num",new Integer(100));
    obj.put("balance",new Double(1000.21));
    obj.put("is_vip",new Boolean(true));
    obj.put("nickname",null);
    out.print(obj);
    out.flush();
  %>

示例 2 - 客户端 XMLHttpRequest

client.html: 
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<script type="text/javascript">
function createXMLHttpRequest(){
  // See http://en.wikipedia.org/wiki/XMLHttpRequest
  // Provide the XMLHttpRequest class for IE 5.x-6.x:
  if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
    throw new Error( "This browser does not support XMLHttpRequest." )
  };
  return new XMLHttpRequest();
}

var AJAX = createXMLHttpRequest();

function handler() {
  if(AJAX.readyState == 4 && AJAX.status == 200) {
     var json = eval('(' + AJAX.responseText +')');
     alert('Success. Result: name => ' + json.name + ',' + 'balance => ' + json.balance);
  }else if (AJAX.readyState == 4 && AJAX.status != 200) {
alert('Something went wrong...');
  }
}

function show(){
  AJAX.onreadystatechange = handler;
  AJAX.open("GET", "service.jsp");
  AJAX.send("");
};
</script>

<body>
  <a href="#" onclick="javascript:show();"> Click here to get JSON data from the server side</a>
</html>

您可以找到有关这些示例的更多信息 这里

附言!

您还应该研究 Dave Newton 建议的解决方案。他比我更有经验,并且知道他在说什么。

Hello Ging3r,

Normally, JSP websites require a JSON plugin to encode/decode JSON messages.

JSON.simple is a good example of a JSON plugin. The JSON.simple website also provides tutorials for setting up JSON on JSP websites.

If you prefer using plugins specific to Struts, there are a couple of JSON plugins for Struts2 on Apaches website.

Edit

I’m absolutely not an expert on JSP, and know nothing about the JSON Struts plugin you are using, although I know a little bit about json-simple.

Nevertheless, the following two examples make sense for me. The examples are from the tutorial mentioned above.

Example 1 - Server side JSP encoding

service.jsp: 
  <%@page contentType="text/html; charset=UTF-8"%>
  <%@page import="org.json.simple.JSONObject"%>
  <%
    JSONObject obj=new JSONObject();
    obj.put("name","foo");
    obj.put("num",new Integer(100));
    obj.put("balance",new Double(1000.21));
    obj.put("is_vip",new Boolean(true));
    obj.put("nickname",null);
    out.print(obj);
    out.flush();
  %>

Example 2 - Client side XMLHttpRequest

client.html: 
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<script type="text/javascript">
function createXMLHttpRequest(){
  // See http://en.wikipedia.org/wiki/XMLHttpRequest
  // Provide the XMLHttpRequest class for IE 5.x-6.x:
  if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
    throw new Error( "This browser does not support XMLHttpRequest." )
  };
  return new XMLHttpRequest();
}

var AJAX = createXMLHttpRequest();

function handler() {
  if(AJAX.readyState == 4 && AJAX.status == 200) {
     var json = eval('(' + AJAX.responseText +')');
     alert('Success. Result: name => ' + json.name + ',' + 'balance => ' + json.balance);
  }else if (AJAX.readyState == 4 && AJAX.status != 200) {
alert('Something went wrong...');
  }
}

function show(){
  AJAX.onreadystatechange = handler;
  AJAX.open("GET", "service.jsp");
  AJAX.send("");
};
</script>

<body>
  <a href="#" onclick="javascript:show();"> Click here to get JSON data from the server side</a>
</html>

You can find more information about these examples here.

PS!

You should also look into the solution suggested by Dave Newton. He is far more experienced than me, and knows what he is talking about.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文