I'm experimenting a little bit with Django and Ajax. I want to make a simple view with a button that when someone clicks on it, the website alerts the data taken from another view in my views.py
, which is an HttpResponse that says "foo". Currently, when I click on the button, nothing appears. I was wondering what has gone wrong here. My code is as follows:
In my views.py
:
from django.shortcuts import render
from django.http import JsonResponse
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request,"ajax/index.html")
def test(request):
return HttpResponse("foo")
In my index.html
:
<body>
<div> hello world </div>
<button class="btn"> click this </button>
</body>
<script>
$(".btn").click(function(){
$.ajax({
url: '//http://127.0.0.1:8000/test/',
type: 'GET',
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("something went wrong")
}
});
});
</script>
In my urls.py
:
from django.contrib import admin
from django.urls import path
from ajax import views as ajax_views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/',ajax_views.index,name="index),
path('test/',ajax_views.test,name="test")
]
Thank you for your time!