Reputation: 79
In Django, I am trying to get a json using ajax. Before doing that, I will try to output a generic string instead of json. However, no matter how I try, the data does not print properly. The character "Good" in result.html is output normally. I thought I used url incorrectly, so I tried it several ways and it did not work.
I would appreciate it if you could look at the code and let me know in detail what went wrong.
Here is my code:
result.html
<!DOCTYPE html>
<html>
<head>
<title>Hello Bubble Chart</title>
<meta charset="utf-8">
</head>
<body>
<h1> Good</h1>
<hr>
<script src="http://code.jquery.com/jquery-lastest.min.js"></script>
<script type="text/javascript">
$.ajax({
type: "GET",
//dataType: "json",
url: "/help/",
data: {},
success: function(response){
alert(data);
$("body").append(data);
}
});
</script>
</body>
</html>
views.py
def json_data(request):
if request.is_ajax():
message = "Yes, AJAX!"
else:
message = "Not AJAX"
return HttpResponse(message)
urls.py
urlpatterns = [
url(r'^inputTest/$', views.input_V, name='input_V'),
url(r'^inputTest/result/$', views.result, name='result'),
url(r'^inputTest/process/$', views.process, name='process'),
url(r'^inputTest/help/', views.json_data, name='json_data'),
url(r'^admin/', admin.site.urls),
]
Upvotes: 0
Views: 589
Reputation: 87134
The first thing to fix is the typo in the URL of the jquery CDN - it should be:
http://code.jquery.com/jquery-latest.min.js
not
http://code.jquery.com/jquery-lastest.min.js
i.e. ...latest...
not ...lastest...
.
Without jquery the ajax call has no chance of working.
Upvotes: 0
Reputation: 9245
Your view should be like this,
def json_data(request):
if request.is_ajax():
message = "Yes, AJAX!"
else:
message = "Not AJAX"
return JsonResponse(dict(message, message))
Also, your ajax request should be,
If you are on the result view,
$.ajax({
type: "GET",
url: "/help/",
success: function(data){
alert(data);
$("body").append(data);
}
});
Upvotes: 1