如何解决从Django视图中获取HttpResponse时,Ajax获取请求不起作用
我正在对Django和Ajax进行一些试验。我想用一个按钮做一个简单的视图,当有人单击它时,网站会在我的views.py
(它是一个HttpResponse,说“ foo”)中警告从另一个视图获取的数据。当前,当我单击按钮时,什么也没有显示。我想知道这里出了什么问题。我的代码如下:
在我的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")
在我的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>
在我的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")
]
谢谢您的时间!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。