简体   繁体   中英

How to pass variable from java to javascript?

I have a edit funtion in javascript jsp in which i need to pass the id of a book to the java method. In the java method, i use that id to search through a table from database and to find the type of book. (category) Then, I need to go back to the jsp (javascript function) and to load that type of book into a field.

JAVASCRIPT inside JSP:

<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:

    @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"));
    }

By doing so, the type from javascript is null... How to change that? (the type from java is holding the wanted value). BookDao.getTypeCategory is using the id to search through the database table and to retrieve the needed type.

You need to use @ResponseBody and inside the ajax use the success callback to get the value of success of ajax.

DataTypeOfReturn is the type of the data which you want to return & it can be 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM