简体   繁体   中英

Request JSON object from server?

i have a JSON object in server side:

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 ?

I am using JSF 2 with Pure JavaScript with no other libraries.

In HTTP, the server doesnt send anything to client-side. 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).

See http://api.jquery.com/jQuery.getJSON/ to get a JSON String from JavaScript. 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:

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

The correct way, however, is to use a fullworthy JSON web service for this. JSF is a component based MVC framework, not a JSON web service. For that the Java EE stack offers the JAX-RS API. Long answer short: 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. You only need to take into account that when used in combination with JSF, this can be used for pure presentation only.

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. It can be done by jQuery function getJSON. It will get the json string and parse it inti hash, then you have to process it for your needs. API documentation

send your json object to response and get the response in the javascript. use eval function to evaluate json object.

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

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