0

I've seen many similar issues, but they didn't provide answer for my question. My Server form JSON string and put it into response:

List<String> list = getSomeList();
JSONArray jsArray = new JSONArray(list);
System.out.println(jsArray);
response.setContentType("application/json");
response.getWriter().write(jsArray.toString());

But in my javascript handle function when I alert response, it alert ALL page!

function handleResponse(){    
 if(http.readyState == 4 && http.status == 200){  
  var response = http.responseText;
   if(response){ 
     alert(response); //alert all page!
     var list = JSON.parse(response.toJSON()); //doesn't work! 
 }       
} 

Question: how could I separate only jsArray in javascript?

P.S. As I understand, my JSON.parse(response.toJSON()) doesn't work because response contain the whole page?

4
  • 1
    does jsArray.toString() return JSON object? Commented Apr 4, 2013 at 19:23
  • in debug: jsArray - JSONArray jsArray.toString - "["Harkiv","Kiev","Lviv"]" Commented Apr 4, 2013 at 19:29
  • I don't know java, but try closing your response writer right after writing your jsArray. It's probably something like response.getWriter().close(); Client-side, JSON.parse() should be sufficient. No need to do response.toJSON() Commented Apr 4, 2013 at 19:32
  • response.getWriter().close() - Yes, it is what I want. Thank you ) Commented Apr 4, 2013 at 19:36

1 Answer 1

1

Disclaimer: I don't know java.

Server-side, the problem is probably that your response is not closed after writing your JSON Array, allowing other (html) text to be written. Try this:

response.setContentType("application/json");
response.getWriter().write(jsArray.toString());
response.getWriter().close();

Client-side, responseText is a string, and strings don't have a toJSON() function defined.

var list = JSON.parse(http.responseText); 

should suffice.

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.