Java Spring JSON Call with Examples

do this JSON Call On Any event of the html element
to fetch the data from database
Like
<input type="button" Value="Call addMyData" onclick="addMyData()"  />

function addMyData()
{
var name="Hello";
var address="Ahmedabad";
$.ajax({
type : "POST",
dataType : "json",
url :"/hello/addData",    //////THis is RequestMapping Value of controller
                          //  if you are working in spring u cal also write 
                          ///  URL  like url: realativePath/adaData.php  or
                          ///            url: realativePath/addData.jsp  etc
data : {
name:name,
address:address
},
success : function(response) {
console.log(response);    ////This is response from the server After the                                 success of ajax call
},
error:function(s,st){                ///this will be executed if ajax call is failed  or return with error  ////
alert("error"+s);
}
}).done(function() {
alert("Call is Completed");     /////this will execute when ajax call complete
});
}


IN CONTROLLER

you just need to return json data if u want to return any data 


just create a json object


JSONObject json=new JSONObject()


append some data to it

json.put("addedName",name)  // where name is your        variable in controller 
and send this in to response

response.getWriter().write(json.toString());
Now if u want to get this data in json call success

success:function(response){
alert(response.addedName);
}



IF any query ask me, i will back to you as fast as posible thanks for visiting this blog




No comments:

Post a Comment