0

I'm currently working on a school project which consists of developing a game using Struts2/JSP.

The problem I have is I can't get Data from my ActionClass to my JSP using jQuery. It works great the other way and I found multiple sources to do so.

Here is my minimized GameAction.class:

private String playerColor;
private Map<String,Object> applicationMap;

public String execute (){

playerColor = ((Joueur)applicationMap.get("joueur")).getPlayerColor();
    return SUCCESS;
}

NOTE: everything has a getter/setter.

game.js :

var $playerColor;
$(window).on('load', function () {

$.ajax({
    type : "GET",
    url : "gotoGameAction",
    data : "playerColor=",
    success : function (data) {
    $playerColor = data;
    var html = "<h2>" + $playerColor.toString() + "</h2>";
    $("#playerColor").html(html);
  }

})

});

Struts.xml:

<package name="default" extends="json-default" namespace="/">
    <action name="gotoGameAction" class="actions.logins.GameAction">
        <result name="success" type="json">/WEB-INF/views/game.jsp</result>
    </action>
</package>

This output I have on my JSP is : [object Object].

I really can't get what's going on there.

Roman C
  • 49,761
  • 33
  • 66
  • 176

2 Answers2

0

I found some of mistakes in your code. It may helpful to you.

In struts.xml

Its

<result name="success" type="json">playerColor</result>

instead

<result name="success" type="json">/WEB-INF/views/game.jsp</result>

Here type json so variable to be passed.

And playerColor should have getter method in GameAction.

In Ajax call simply

success : function (data) {
    $("#playerColor").html("<h2>" + data + "</h2>");
}
SatyaTNV
  • 4,137
  • 3
  • 15
  • 31
0

You might not understand what is a JSON result type and how the content is provided by the action which is executing this result type.

To get more about plugin and documentation see JSON Plugin.

You can also look in the source code for the class which is being executed the JSONResult. Then you see that

/**
 * This result type doesn't have a default param, null is ok to reduce noise in logs
 */
public static final String DEFAULT_PARAM = null;

However such noise sometimes is helpful if you are debugging the code.

That makes no any sense in your code

<result name="success" type="json">/WEB-INF/views/game.jsp</result>

The you need to dig into the tutorial and examples how to use this result. One of them you can find here.

Another link might help you to decide whether you need a json result or use any other result suitable for JSON response.

Combining all that together will make an idea to rewrite your code to get it working.

Roman C
  • 49,761
  • 33
  • 66
  • 176