简体   繁体   中英

javascript function with json argument from jsp

Problem calling js function with json argument form a jsp.

JSP Code :

  <%
JSONObject json = (JSONObject)request.getAttribute("json");
out.println("json : " + json); // able to print this json object
  %>

  <body onload="printReviews(${json})">
  </body>

Javascript Code :

  function printReviews(jsonobj){
    alert('jsonobj : ' + jsonobj);
  }

Also, I tried the scriptlet way : onload="printReviews('<%=json%>')".

I don't understand why this is failing to get the JSON object in javascript. Please suggest me any other alternatives, to pass the JSON object to the javascript function that I'm getting from my Servlet.

I think this is because for the code

body onload="printReview(${json})"

I believe your jsp EL ${json} with the JSON object gets coerced to a string and is replaced by its actual contents as the page is rendered. As this is JSON format you will obviously have something like {"mykey":"myvalue"}. So what is happening is your printReview function actually becomes something like,

body onload="printReview({"mykey":"myvalue"})"

as you can see this cannot execute unless you escape the double quotes or use single quotes to wrap the printReview function, something like

body onload='printReview(${json})'

This should work but again until there is any single quote in your json response. At which point you will have to escape that as well

Now when you pass a variable(jsonData in your case) in printReview, this JSON object to string conversion is not happening hence you do not get that when you change your code to

body onload="printReviews(jsonData);"

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