How does Django send data back to be displayed by Ajax?
In Django, you can use the JsonResponse to return data to be displayed by Ajax. Here is an example:
from django.http import JsonResponse
def my_view(request):
data = {'name': 'John', 'age': 25}
return JsonResponse(data)
In the code above, the JsonResponse converts the dictionary data to JSON format and sends it back as a response to Ajax. The returned data can be accessed in the front-end Ajax request through the data parameter.
$.ajax({
url: '/my_view',
dataType: 'json',
success: function(data) {
// 处理返回的数据
console.log(data.name);
console.log(data.age);
}
});
In the code snippet above, Ajax specifies the expected response data type as JSON by using the dataType: ‘json’ parameter. The data parameter in the success callback function will contain the returned JSON data. You can further handle it as needed.