Reputation: 7110
Here's my POST:
$("#checkin-button").click(function() {
var mid = $("input#mid").val();
var dataString = 'mid='+mid;
$.ajax({
type: "POST",
url: "/game-checkin",
data: dataString,
success: function() {
$('#checkin-form').html("<div id='message'></div>");
$('#message').html("<h2>You are checked in!</h2>");
}
});
return false;
});
I am sending back a JSON string and want to use it in my Django template. How do I capture that response for display in the template?
Upvotes: 1
Views: 3851
Reputation: 3159
You can simply do this :
$.post("/game-checkin", {mid: mid }, function(data){
//response in json format. Example: data.something
}, "json");
Upvotes: 1
Reputation: 7906
Use this function as callback:
success: function(response) {
alert(response);
}
The response will be what your server returns, but as text. If you have to use that JSON effectively in Javascript you have to use the eval() function like this: eval('(' + response ')'); and it will evaluate the JSON expression so you can assign it to an object like this:
success: function(response) {
var responseObj = eval('(' + response + ')');
// use responseObj here
}
I don't know about Django, but this is how you get the response and evaluate it as JSON.
Upvotes: 0
Reputation: 2180
From the API
success(data, textStatus, XMLHttpRequest)Function
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the 'dataType' parameter; a string describing the status; and the XMLHttpRequest object (available as of jQuery 1.4). This is an Ajax Event.
I think you'll have to use parseJSON() to convert it.
Upvotes: 2