How to use AJAX to call the API interface that you wrote in Django?

You can implement calling your own API interface in Django using AJAX by following these steps:

  1. To create an API interface: First, it is necessary to define your own API interface in Django, which can be achieved by using either Django REST framework or Django’s view functions.
  2. Write front-end code: Include jQuery or another AJAX library in the front-end page, and write AJAX requests to call the API interface.
$.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);
    }
});
  1. Configure CORS: If the API interface and the front-end page are not in the same domain, it is necessary to set up CORS (Cross-Origin Resource Sharing) configuration in Django to allow cross-origin requests.
CORS_ORIGIN_ALLOW_ALL = True
  1. Write view functions for API interfaces: In Django, write view functions for API interfaces to handle AJAX requests and return the corresponding data.
from django.http import JsonResponse

def api_endpoint(request):
    data = {
        'message': 'Hello, world!'
    }
    return JsonResponse(data)
  1. Set up URL routing: associate the URL of the API endpoint with the corresponding view function.
from django.urls import path
from .views import api_endpoint

urlpatterns = [
    path('api/endpoint/', api_endpoint, name='api_endpoint'),
]

By following the steps above, you can use AJAX to call your own API in Django. Retrieve data from the API with AJAX requests on the front-end page and implement the corresponding interactive logic.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds