简体   繁体   English

从服务器请求JSON对象?

[英]Request JSON object from server?

i have a JSON object in server side: 我在服务器端有一个JSON对象:

String jsonText = JSONValue.toJSONString(users);

and i want to send it to client side to be used in a javascript function, how to do that ? 我想将它发送到客户端以用于javascript函数,该怎么做?

I am using JSF 2 with Pure JavaScript with no other libraries. 我在没有其他库的情况下将JSF 2与Pure JavaScript一起使用。

In HTTP, the server doesnt send anything to client-side. 在HTTP中,服务器不会向客户端发送任何内容。 The client-side asks for some resource using a request, and the response contains the resource. 客户端使用请求请求某些资源,响应包含资源。

Make the JavaScript function send an AJAX request to the server, and make the server answer with this JSON string in the response (by writing the JSON String to the response writer). 使JavaScript函数向服务器发送AJAX请求,并使服务器在响应中使用此JSON字符串进行应答(通过将JSON字符串写入响应编写器)。

See http://api.jquery.com/jQuery.getJSON/ to get a JSON String from JavaScript. 请参阅http://api.jquery.com/jQuery.getJSON/以从JavaScript获取JSON字符串。 The server code is as simple as 服务器代码很简单

response.getWriter().print(jsonText);

The easiest way is to let JSF print the string representation of the JSON object as a JS variable in the same view: 最简单的方法是让JSF在同一视图中将JSON对象的字符串表示形式打印为JS变量:

<script>var users = #{bean.usersAsJson};</script>

The correct way, however, is to use a fullworthy JSON web service for this. 但是, 正确的方法是为此使用完全有价值的JSON Web服务。 JSF is a component based MVC framework, not a JSON web service. JSF是基于组件的MVC框架,而不是JSON Web服务。 For that the Java EE stack offers the JAX-RS API. 为此,Java EE堆栈提供了JAX-RS API。 Long answer short: Servlet vs RESTful . 长话短说: Servlet vs RESTful Use this preferably in combination with jQuery or whatever JS framework which is able to send Ajax requests and manipulate the HTML DOM tree in basically an oneliner. 最好结合使用jQuery或任何JS框架,它能够发送Ajax请求并基本上在oneliner中操作HTML DOM树。 You only need to take into account that when used in combination with JSF, this can be used for pure presentation only. 您只需要考虑将其与JSF结合使用时,只能用于纯演示

The browser must request it, ie that string must sit somewhere in a request handling chain; 浏览器必须请求它,即该字符串必须位于请求处理链中的某个位置。 set the response to that string and the browser will receive it. 将响应设置为该字符串,浏览器将收到它。

I think you wanted to say response the json string. 我想你想说响应json字符串。 It can be done by jQuery function getJSON. 可以通过jQuery函数getJSON完成。 It will get the json string and parse it inti hash, then you have to process it for your needs. 它将获取json字符串并将其解析为inti哈希,然后必须根据需要对其进行处理。 API documentation API文档

send your json object to response and get the response in the javascript. 发送您的json对象进行响应,并在javascript中获取响应。 use eval function to evaluate json object. 使用eval函数评估json对象。

var jsonObject = eval('(' + request.responseText + ')');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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