struts2 ajax call response always shows null

时间:2015-09-24 04:59:32

标签: java ajax jsp struts2

I am trying to call the struts2 action class from my jsp using ajax. I can hit the action class and able to pass the parameters to action class. But the response that comes from action class to my ajax request is always null

All setters and getters are set correctly and they are working fine when I see in debug sysouts

Action Class

@Override
@Action(value = "/search",
          results = { @Result(name = "success", type="json")})
public String execute() throws ParseException
{


    this.setName(this.term+": "+this.pos);
    System.out.println("Name: "+Name);

    JSONObject json = (JSONObject)new JSONParser().parse(Name);


    return ActionSupport.SUCCESS;
}

jsp

function Search()
{
    var term = document.getElementById("term").value;
    var pos = document.getElementById("pos").value;
    var itr = document.getElementById("itr").value;
    var pri = document.getElementById("pri").value;
    var atb = document.getElementById("atb").value;
    var jsonData = {};

    jsonData.term = term;
    jsonData.pos = pos;
    jsonData.itr = itr;
    jsonData.pri = pri;
    jsonData.atb = atb;

     $.ajax({
         type: "POST",
         url: "search",
         dataType: "json",
         data: jsonData,
        success: function(response){
            console.log(""+response);
            alert('Name: '+response.Name);
            //alert('Length: '+data[0].length);

          /*  $.each(data[0],function(index, value){
                alert("value " +value);
               });*/
            },
     error:  function(response){
         alert(response);
         alert(response.length);

         $.each(response,function(index, value){
            alert("value " + value);
            });
     }

     });

} 

I can see the response always as null. I am not sure what is going wrong, but seems the coding part is correct. Am I doing some mistake in ajax call?

1 个答案:

答案 0 :(得分:1)

  1. 如清楚解释in this answer,您需要使用JSON插件,它将序列化整个操作(或在需要时单个根对象)。您自己不需要自己进行解析,只需评估name变量。
  2. 要将JSON从JSP发送到操作,您需要在堆栈中使用JSON拦截器。
  3. 确保你拥有所有东西的吸气剂和镶嵌剂。
  4. 您的Name变量应为name,包括Java和Javascript。只有访问者/变异者应该使用大写的N(getNamesetName)。
  5. 如果错误仍然存​​在,请仔细检查控制台和日志文件是否存在错误,并将devMode设置为true。
  6. 由于这条评论太过分了,我已将其转化为答案:)