如何使用ajax从服务器端检索Map对象
我有一个jsp页面。在 jsp 页面中,我执行 ajax 请求,作为响应,我想发送一个 Map 对象。我的第一个问题是这可能吗?
其次,如果可以发送 Map 对象,我如何在 javascript 端检索它以及如何获取所有值。
可能我想将以下内容从服务器发送到 jsp 页面。
one String Object.
one List<C>
one int Object
one List<D>
I have a jsp page. In the jsp page I do a ajax request and in response I would like to send a Map object. My first question is that is that possible.
Secondly if it's possible to send a Map object how does i retrieve it in the javascript side and how I can get all the values.
Probably I would like to send the following things from server to jsp page.
one String Object.
one List<C>
one int Object
one List<D>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要回答你的问题,这本质上是不可能的。
您的 jsp 页面本质上是在服务器端执行的,您的响应通过 http 发送回您的浏览器。由于您正在发出 ajax 请求,因此您的 http 响应将包含 javascript 代码。此时您正在谈论两种不同的语言和运行时。即Java 和javascript。所以你不能直接在javascript中使用Map(这是一个java实现)。
相反,您可能想要尝试的是从 java 服务器端发送 json 响应。这可以很容易地完成,因为 javascript 是一种解释性语言。 JSON 具有名称/值对的对象,本质上就是您想要从 Map 获得的对象。
您也许可以使用像 DWR 这样的库,它会为您完成管道工作,使您看起来像是在本地调用远程 Java 类。但在幕后,还有很多事情在发生。
To answer your question, this is not possible inherently.
Your jsp page is essentially executed on the server side and your response is sent back over http to your browser. Since you are making an ajax request your http response will consist of javascript code. At that point you are talking of two different languages and runtimes. i.e Java and javascript. So you cannot directly be using Map (which is a java implementation) in javascript.
Instead what you might want to try out is send a json response from your java server side. This can easily be done as javascript is an interpreted language. JSON has objects which is a name/value pair and is essentially what you want from a Map.
You might be able to use a library like DWR which does the plumbing for you to make it seem like you are invoking remote Java classes locally. But under the hoods there is a lot of stuff that goes on.
这可以使用 DWR 来完成。
DWR 入门
使用 DWR 使 AJAX 变得简单
面向 Java 开发人员的 Ajax:使用直接 Web 远程处理的 Ajax
DWR 中的 Bean 和对象转换器
This can be done using DWR .
Getting Started with DWR
AJAX made simple with DWR
Ajax for Java developers: Ajax with Direct Web Remoting
Bean and Object convertors in DWR