javascript - 如何将变量从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 搜索数据库表并检索所需的类型。
解决方案
您需要使用@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
}
推荐阅读
- java - 在父活动中调用选项卡片段方法
- unity3d - 如何在 Unity 中进行场景擦除过渡?
- sql-server - 为其他用户锁定表
- mysql - 除了 Laravel 中的查询
- javascript - 将设置注入 webpack 应用程序
- node.js - Sublime 插件找不到 nodejs
- python - 如何管理以 UTF-8 格式发送数据的 API (DeepL)?
- python - Plotly:如何使用 go.Contour 更改等高线的比例?
- python - Dramatiq ModuleNotFoundError
- python-3.x - 使用 Pandas 连接共享行值中的列值