首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将变量从java传递到javascript?

如何将变量从java传递到javascript?
EN

Stack Overflow用户
提问于 2019-05-29 23:10:41
回答 1查看 146关注 0票数 0

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

JSP中的JAVASCRIPT:

代码语言: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>

JAVA:

代码语言:javascript
复制
    @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搜索数据库表并检索所需的类型。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-29 23:17:12

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

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

代码语言:javascript
复制
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
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56363688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档