在Django中使用AJAX调用自己写的API接口可以通过以下步骤实现:
创建API接口:首先需要在Django中定义自己的API接口,可以使用Django REST framework或者Django的视图函数来实现。
编写前端代码:在前端页面中引入jQuery或者其他AJAX库,然后编写AJAX请求来调用API接口。
$.ajax({ url: '/api/endpoint/', // API接口的URL type: 'GET', // 请求类型,可以是GET或者POST等 success: function(data) { // 请求成功时的处理逻辑 console.log(data); }, error: function(xhr, status, error) { // 请求失败时的处理逻辑 console.log(status + ': ' + error); } }); CORS_ORIGIN_ALLOW_ALL = True from django.http import JsonResponse def api_endpoint(request): data = { 'message': 'Hello, world!' } return JsonResponse(data) from django.urls import path from .views import api_endpoint urlpatterns = [ path('api/endpoint/', api_endpoint, name='api_endpoint'), ] 通过以上步骤,就可以在Django中使用AJAX调用自己写的API接口了。在前端页面中通过AJAX请求获取API接口返回的数据,并实现相应的交互逻辑。