我在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>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"));
}通过这样做,javascript中的类型为空...如何改变这一点?( java中的类型包含所需的值)。BookDao.getTypeCategory使用该id搜索数据库表并检索所需的类型。
发布于 2019-05-29 23:17:12
您需要使用@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
}https://stackoverflow.com/questions/56363688
复制相似问题