Mahmoud Saleh
Mahmoud Saleh

Reputation: 33605

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.

Upvotes: 1

Views: 1680

Answers (5)

BalusC
BalusC

Reputation: 1108902

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.

Upvotes: 1

Ramesh Kotha
Ramesh Kotha

Reputation: 8322

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 + ')');

Upvotes: 0

freeze
freeze

Reputation: 566

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

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691825

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);

Upvotes: 2

Nicolas78
Nicolas78

Reputation: 5144

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.

Upvotes: 0

Related Questions