1

I am using struts2 and and jquery to fetch value from server. Here execute() method is calling properly but in jsp value is not shown.

Action class

 package example;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorld extends ActionSupport {

    private String name;
    private String welcomeMessage;

    @Override
    public String execute() {

        System.out.println("Inside Action name is " + getName());
        setWelcomeMessage("Welcome " + getName() + "!!");
        System.out.println(getWelcomeMessage());
        return SUCCESS;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getWelcomeMessage() {
        return welcomeMessage;
    }

    public void setWelcomeMessage(String welcomeMessage) {
        this.welcomeMessage = welcomeMessage;
    }
}

struts.xml

 <package name="example1" extends="json-default">
        <action name="test" class="example.HelloWorld">
            <result  type="json"></result>
        </action>
    </package>

Jsp page

<html>
    <head>
        <title>JSON EXAMPLE</title>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    </head>
    <body>
        <form action="" id="introForm">
            <label for="name">Enter Your Name</label>
            <input name="name" id="name">
            <input type="button" id="button1" value="Submit">
        </form>
        <div class="result"></div>
        <script>
            $("#button1").click(function() {

                var name1=$("#name").val();
                alert("name is "+name1);//showing entered name
                $.getJSON('test', { name: name1}, function(data) {
                    alert(data); // not calling
                    $('.result').html(data.welcomeMessage);
                    return false;
                });
            });
        </script>
   </body>
</html>

I have included jsonplugin-0.34.jar in my lib folder.

Program is executing properly, not showing any error. Here I am trying to fetch welcomeMessage from action in <div class="result"></div>.

Problem is it is not showing JSON value in jsp page.

Alert alert(data); inside $.getJSON('test', { name: name1}, function(data) { is not calling. Please see where is the problem.

4

1 回答 1

1

您的代码很好(除了<input>不是(自我)关闭的 s ,以及正文中的脚本应该留在$( document ).ready()片段内的头部);

我猜你只是被 S2 JSON 插件的下载页面愚弄了。那个页面很旧而且没有维护,0.32 和 0.34 真的是旧版本;

为此,请始终参考 Maven 存储库:

http://mvnrepository.com/artifact/org.apache.struts/struts2-json-plugin

并确保选择与您的 struts2-core JAR 匹配的版本。

于 2013-07-08T08:45:19.763 回答