How to specify JSON url to js method in a JSF based application
I am implementing a multiselect autocomplete textbox (similar to one that Stackoverflow
uses for tags
input), using fcbkComplete
. For implementation, I need to transfer JSON objects to a Jquery function from JSF. (There's a need to specify JSON url as parameter to fcbkComplete
).
开发者_运维百科 $("select0").fcbkcomplete({
json_url: "fetched.txt"
});
I am using JSF 2.0 with Primefaces 3.0M3. I would appreciate if someone can show me a direction as to how I can specify a JSON url to a js method in a JSF based application.
Thanks
At its simplest, you can just let a JSF managed bean getter return the desired JSON as a String
and assign it to a JS variable which is inlined in the view template:
<script>
var json = #{bean.json};
// ...
</script>
(note that the variable value is unquoted! i.e. using var json = '#{bean.json}';
won't work out)
You can if necessary use among others Google Gson to easily convert between Java objects and JSON strings. You can if necessary put that <script>
inside a <h:panelGroup>
with an id
so that it can be re-rendered upon an ajax request. You can if necessary end up wrapping this in a composite component.
True, it's very spartan, PrimeFaces may have better ways for approaching this, but I'm not aware of any.
As a completely different alternative, when the data does not depend on anything in the JSF context (expect of maybe some session scoped managed bean, which is available as a HttpSession
attribute anyway), you can also create a simple servlet which does the job upon a jQuery.ajax()
call. You can find several examples in this answer: How to use Servlets and Ajax?
精彩评论