调用JavaScript/jquery中的bean方法

Call a bean method in JavaScript/jquery?

本文关键字:bean 方法 中的 jquery JavaScript 调用      更新时间:2023-09-26

我需要调用JavaScript和/或jQuery中的bean方法,并且必须根据方法返回的值做出决定。

我们该怎么做?

为了使JavaScript和Java Servlet能够通信,正如您所建议的,您将需要一个AJAX调用,您可以使用jQuery。

首先,设置一个新的Servlet,它将充当各种AJAX web服务。我们将保持简单,因此只需实现doGet()方法来处理HTTP GET请求。在该GET方法中,查看查询字符串中的特定参数。

的例子:

myServlet?myArgument1=value1

(在这个例子中确保你的web.xml将你的Servlet映射到/myServlet)

在Java代码中处理请求(从bean获取值),然后基于该请求构建JSON响应。例如,您可以返回:

{ "response": "my value" }

Java端完成。

在JavaScript端,你需要启动一个$. getjson()查询。

你可以这样做:

var myRequest = $.getJSON("myServlet?myArgument1=" + value1, 
    function(data) 
    {
        console.log( "success" );
        // Process the 'data', which is the JSON response.
        var returnedJson = JSON.parse(data);
        var value = returnedJson.response; // now equals "my value"
        // ...
    })     
    .fail(function() 
    {
        // Handle errors here
        console.log( "error" );
    })
    .always(function() 
    {
        // If you need to do something whether the request was success or fail,
        // do it here.
        console.log( "complete" );
    });

在我看来这是最直接的方法。如果你正在寻找一个Java库,它可以很容易地让你解析或创建JSON,而不是"硬编码",你可以看看JSON -smart。https://code.google.com/p/json-smart/