I am trying to make crossdomain calls using jQuery, but so far pretty unsuccessful. My HTML file is on my ‘C:/Temp’ folder name ‘test.html’. My HTML code is below —
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
<input id="first_name" type="text" value="khan" />
<input id="clickme" type="button" value="Click Me!"/>
<script type="text/javascript">
$(document).ready(function() {
$("#clickme").click(function(){
$.ajax({
url: 'http://localhost:8008/qm/profile/' + $("#first_name").val() + "/",
type: "GET",
dataType: "jsonp",
crossDomain : true,
success: function(response)
{
alert(response.responseText);
},
error: function()
{
alert("fail");
},
});
});
});
</script>
</body>
</html>
Now on the server side I have a little python code that looks like this —
def profile(request, username):
fullname = ''
if username == 'khan':
fullname = 'Khan Hannan'
data = {'fullname': fullname}
print data
return HttpResponse(json.dumps(data))
The python code is inside DJango project. If I make a straight call to the URL (‘http://localhost:8008/qm/profile/khan’), I get a JSON response back from my server, but when I put the same URL through jQuery, I don’t get any response and it fails.
Any suggestion?
JSONP works by wrapping your JSON in a function and then executing the function to get the code object.
This is done by sending a callback querystring value to the server which it is then suppose to wrap the JSON object with.
If you inspect the request going out to your server you should see a value being send along called
callback=jquery[long number].http://en.wikipedia.org/wiki/JSONP