VB_
VB_

Reputation: 45692

Handle JSON server response in javascript

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?

Upvotes: 0

Views: 1339

Answers (1)

Bart
Bart

Reputation: 27205

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.

Upvotes: 1

Related Questions