javascript 从javascript调用java方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16494787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:55:15  来源:igfitidea点击:

Call java method from javascript

javajavascript

提问by tetrapack

I have a web jsp web application. In one page I need two dropdownlist. When I will select a value from dd1 then second dropdown will be fill according this value. How I can call java function from dropdown 1 change event in javascript or jQuery?

我有一个 web jsp web 应用程序。在一页中,我需要两个下拉列表。当我从 dd1 中选择一个值时,第二个下拉列表将根据该值进行填充。如何从 javascript 或 jQuery 中的下拉列表 1 更改事件调用 java 函数?

I got example but that is calling jsp page but I need to java method and send parameter what i got from dropdown1

我有例子,但那是调用jsp页面,但我需要java方法并发送我从dropdown1得到的参数

This is my dropdown dd1. So if I select tom I have to related information of tom in dd2.

这是我的下拉菜单 dd1。所以如果我选择tom,我必须在dd2中找到tom的相关信息。

            <td>
              <select  id="dd1">
                    <option value="1">john</option>
                    <option value="2">Tom</option>
              </select>

          </td>
        </tr>
        <tr>
          <th> Projects </th>
          <td>

              <select id="dd2">
                    <option value="1">pp1</option>
                    <option value="2">pp2</option>
              </select>

          </td>

I have following code

我有以下代码

$(function () {
    var ddVal = '';
    var dropdown = document.getElementById("dd1")
    $(dropdown).focus(function () {
        ddVal = $(this).val();
        }).blur(function () {
        if (ddVal == $(this).val()) {
            $(this).change();
        }
    }).change (function () {

});

For change event of dd1. But I don't know how to call java method from jQuery.

对于 dd1 的更改事件。但我不知道如何从 jQuery 调用 java 方法。

In my application I have a java class where there is a method which return list that I need to load in dd2 dropdown.

在我的应用程序中,我有一个 java 类,其中有一个方法可以返回我需要在 dd2 下拉列表中加载的列表。

Can anyone help me regarding this issue?

任何人都可以帮助我解决这个问题吗?

回答by Powerslave

You should do such things with AJAX.

你应该用 AJAX 做这样的事情。

JavaScript sends the request, your controller utilizes the Java part to carry out what's needed and then passes back a JSON response, based on which your JavaScript manipulates the page.

JavaScript 发送请求,您的控制器利用 Java 部分来执行所需的操作,然后传回 JSON 响应,您的 JavaScript 根据该响应操作页面。



EDIT:编辑:

For example, the script can issue the following request:

例如,脚本可以发出以下请求:

$.ajax({
    "type": "POST",
    "url": "/ajaxAPI/updatedropdown/",
    "data": {
        "selected": selectedMenuItemId
    },
    "success": function (data) {
        var menuItems = data.menuItems;
        dropDownToChange.updateChoices(menuItems);
    }
});

Your controller for such a request might look like:

此类请求的控制器可能如下所示:

public class DropDownListController implements Controller {

    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MenuItem selected = extractSelectionFromRequest(request);
        List<MenuItem> choices = dropDownListService.getMenuFor(selected);
        ModelAndView mav = new ModelAndView("dropDownListAjax.jsp");
        mav.addObject("menu", choices);
    }

    // WARNING! Some error checks are missing!
    private MenuItem extractSelectionFromRequeset(HttpServletRequest request) {
        validateRequest(request);
        return dropDownListService.getMenuItemById(request.getAttribute("selected"));
    }

    // ...

}

And for the view you could have something like:

对于视图,您可以使用以下内容:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
{
    "menuItems": [
        <c:forEach items="${menu}" var="menuItem">
            {
                "url": <c:out value="${menuItem['url']}"/>,
                "caption": <c:out value="${menuItem['caption']}"/>
            },
        </c:forEach>        
    ]
}

The client side JavaScript will then receive a response like:

然后客户端 JavaScript 将收到如下响应:

{
    "menuItems": [
        {
            "url": "http://www.example.com/"
            "caption": "Home"
        },
        {
            "url": "http://www.example.com/news/list/"
            "caption": "News"
        },
        {
            "url": "http://www.example.com/forum/topics/"
            "caption": "Forum"
        },
    ]
}

Please note that the above example might not be 100% correct as there have been a while since I last used JSP (and I'm more comfortable with FreeMarker anyways).

请注意,上面的例子可能不是 100% 正确的,因为我上次使用 JSP 已经有一段时间了(反正我对 FreeMarker 更满意)。

Basically, you invoke part of your web infrastructure that, rather than responding with HTML code, passes back JavaScript Objects based on the results of the requested operation.

基本上,您调用 Web 基础设施的一部分,而不是响应 HTML 代码,而是根据请求操作的结果传回 JavaScript 对象。

Since jQuery is in the client side and JSP is on the server side, you don't have the option of directly calling the remote method. The standard way to do this in the world of the Web is AJAX.

由于 jQuery 在客户端,而 JSP 在服务器端,因此您无法直接调用远程方法。在 Web 世界中执行此操作的标准方法是 AJAX。