Hello All,
I use django 1.4 run on ubutu.
I'm trying to use jquery/ajax to display data returned from a django method.
my file views.py
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
from django.utils import simplejson
from django.core.serializers import serialize
from django.core.serializers.json import DjangoJSONEncoder
import ast
def json_page(request):
to_json = {
"key1" : "value1",
"key2" : "value2"
}
return HttpResponse(simplejson.dumps(to_json), mimetype="application/javascript;charset=UTF-8")
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
my html file:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<h1>Hello World!</h1>
<script>
$('document').ready(function() {
var url = "http://localhost:8000/json/";
$.ajax({
url: url,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain: false,
success: function(data) {
alert(abc);
},
error: function(xhr, textStatus) {
alert("doLogin\n- readyState: " + xhr.readyState + "\n- status: " + xhr.status);
}
});
});
</script>
</body>
</html>
-------------------------------------------------------------------------------------------
I run file html, fire bug return status = 200 (ok). But not return data
Could you help me fix it. Thanks all,
Hi,
You should change the mimetype on HttpResponse from mimetype="application/javascript;charset=UTF-8" to mimetype="application/json; charset=utf-8".