0

I am new to Ajax and would have thought there would be plenty of examples of passing an array from java to ajax; however, I have not been able to find them. I want to pass three strings to ajax and then display them in HTML. My java code is:

System.out.println("Authenticated");
String json = new Gson().toJson(questionList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

The ajax is:

dataType: "json";
alert(responseJson);
var result = $.parseJSON(responseJson); <-- this line fails
$('#question1').val(result.question1);
$('#question2').val(result.question2);
$('#question3').val(result.question3);

The alert displays "Question 1 is a?,Question 2 is b?,Question 3 is c?".

How do I pass each of the strings to display in the HTML. I suspect I need to build the array in java differently as well as receive the result in ajax differently; however, I can not find an applicable example. I do not want to use unstring as the question could contain "," or other delimiter used.

3
  • What json do you get after String json = new Gson().toJson(questionList);? Because from the alert displays, it seems not a valid json string. Commented Mar 26, 2018 at 1:44
  • I added "System.out.println("json = " + json); and the result is: "json = ["Question 1 is a?","Question 2 is b?","Question 3 is c?"]". Commented Mar 26, 2018 at 2:41
  • for me , you are re parsing the string which is already in json. you set application/json , so i don't see the need of parse in ajax Commented Mar 26, 2018 at 3:01

1 Answer 1

1

The responseJosn you get from ajax is already been parsed. No need to parse it again. It's an Array. So the JS code would be like:

dataType: "json";           //this line should not be here
alert(responseJson);
//var result = $.parseJSON(responseJson); <-- this line fails
$('#question1').val(responseJson[0]);
$('#question2').val(responseJson[1]);
$('#question3').val(responseJson[2]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.