Karesh A
Karesh A

Reputation: 1751

Get JSON from response object

<html>
<body>

    <form action="login.do" method="post">
        //.....

        <input type="submit" value ="send">
    </form>
</body>
</html>

In my servlet I will be handle the request and send the json response back. How can I get the json object from the response ?

But we can do this by calling a function when we click the button.

function(){
    $ajax(
        url:"login.do"
        success: function(data){
        //..... 
        }
    )
}

is there any way to do this? Or only using the function call we can do it?

Upvotes: 0

Views: 5679

Answers (2)

xdazz
xdazz

Reputation: 160833

You could set the dataType to json, or you could use the short cut method $.getJSON().

$.getJSON(your_url, function(data) {
  // data here is already an object.
  console.log(data);
});

EDIT: getJSON will use GET request type, for POST, you could do

$.post(your_url, function(data) {
  // data here is already an object.
  console.log(data);
}, 'json');

Upvotes: 2

charlietfl
charlietfl

Reputation: 171679

first argument of success callback that you call data is the json object so long as you include dataType:'json' in ajax options or use shorthand $.post(url[,data][,function(json){}),'json']) method

Read about success callback in $.ajax API :

http://api.jquery.com/jQuery.ajax/

EDIT: Using deffered method

var ajaxCall= $.post( url, dataToServer,'json')


 $.when( ajaxCall).then(function(data){
     var json =data;
 })

Upvotes: 2

Related Questions