I am currently faced with the challenge of passing the MongoDB Query Result in String Format to a JSP Page using Ajax. While I am able to successfully retrieve the data, I am struggling with how to iterate over that data.
Note : The JSON Structure has a Dynamic Schema as shown below
Query Result in String Format
[
{
"_id":"...",
"user":"John Doe",
"hobbies":["1","2","3"],
"address":{
"city":"...",
"state":"...",
"country":"..."
},
"cell":97265xxxxx
},
{
"_id":"...",
"user":"John Doe",
"hobbies":["1","2","3"],
"cell":97265xxxxx
}
...
]
To tackle this issue, I first convert the JSON String into a JavaScript Object using jQuery's parseJSON() method. However, when attempting to loop over the data, I encounter issues with undefined values.
Below is the code snippet
<button>Click Me</button><br/>
<p id="p0"></p>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").on("click",function(){
$.ajax({
url:'QuizDemoServlet',
type:'post',
success:function(data) {
//JSON String is Fetched Successfully
$("#p0").html(data);
var jso = $.parseJSON(data);
alert("JSO " +jso.length);
for(var iterate=0; iterate<jso.length; iterate++){
$("#p1").append(iterate["user"]+"<br>");
$("#p2").append(iterate["hobbies"]+"<br>");
$("#p3").append(iterate["cell"]+"<br>");
}
},
error:function(msg){
alert("Error");
console.log(msg);
}
});
});
});
</script>