首页 > 解决方案 > 如何将变量从java传递给javascript?

问题描述

我在 javascript jsp 中有一个编辑功能,我需要将一本书的 id 传递给 java 方法。在 java 方法中,我使用该 id 从数据库中搜索表并查找书籍的类型。(类别)然后,我需要回到jsp(javascript函数)并将该类型的书加载到字段中。

JSP 中的 JAVASCRIPT:

<script>
function edit(id) {
        jQuery.ajax({
            type: "GET",
            url: "getId",
            data: "id= " + id,
            datatype: "text"
        });
        var type =<%= ((String)request.getAttribute("myType"))%> ;
        console.log("type is " + type);
    }
</script>

爪哇:

    @RequestMapping("/getId")
    public void getId(
            @RequestParam int id,HttpServletRequest request) {
        idBook = id;
        System.out.println("get id book "+id);
        String type= BookDao.getTypeCategory(id);
        request.setAttribute("myType",type);
        System.out.println("request attribute"+request.getAttribute("myType"));
    }

通过这样做,来自javascript的类型为空......如何改变它?(来自 java 的类型持有想要的值)。BookDao.getTypeCategory 使用 id 搜索数据库表并检索所需的类型。

标签: javascriptjava

解决方案


您需要使用@ResponseBody并在ajax 内部使用success回调来获取ajax 的成功值。

DataTypeOfReturn是您要返回的数据类型,可以是int/String

function edit(id) {
  jQuery.ajax({
    type: "GET",
    url: "getId",
    data: "id= " + id,
    datatype: "text",
    success: function(data) {
      console.log(data)
    }
  });
  var type = <%= ((String)request.getAttribute("myType"))%>;
  console.log("type is " + type);
}



@RequestMapping("/getId")
public @ResponseBody DataTypeOfReturn getId(
  @RequestParam int id, HttpServletRequest request) {
  int idBook = id; // add data type here to avoid java error
  System.out.println("get id book " + id);
  String type = BookDao.getTypeCategory(id);
  request.setAttribute("myType", type);
  System.out.println("request attribute" + request.getAttribute("myType"));
  return theValue; // value which you want to return
}

推荐阅读