Django返回数据给ajax,Django返回JsonResponse并在ajax请求中捕获数据

这是我的观点。

我将JsonResponse返回到ajax请求,在这里从我的视图'line_product_total': total,和其他上下文捕获传入的数据def get(self, request, *args, **kwargs):

cart = self.get_object()

product_id = request.GET.get('product')

delete_product = request.GET.get('delete', False)

product_added = False

if product_id:

product_instance = get_object_or_404(Product, id=product_id)

amount = request.GET.get('amount', 1)

try:

if int(amount) < 1:

delete_product = True

return HttpResponse('IntegrityError', delete_product)

except:

raise Http404

cart_product, created = CartProduct.objects.get_or_create(cart=cart, product=product_instance)

if created:

product_added = True

if delete_product:

cart_product.delete()

else:

cart_product.amount = amount

cart_product.save()

if not request.is_ajax():

return HttpResponseRedirect(reverse('e_commerce:cart'))

# return cart_product.cart.get_absolute_url

if request.is_ajax():

try:

total = cart_product.line_product_total

except:

total = None

data = \

{

'deleted': delete_product,

'product_added': product_added,

'line_product_total': total,

}

return JsonResponse(data)

cart = Cart.objects.get(pk=cart.pk)

return render(request, 'sales/cart.html', {'cart': cart})

js

^{pr2}$

模板

{{ product.line_product_total }}

简言之,我无法在ajax中捕捉变量line_product_total

它只是在说Unresolved variable line_product_total

但我要发送这个变量。什么问题?

伙计们至少告诉我问题本身不能解决什么

提前感谢:)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在 Django ,您可以使用 Django REST framework 来编写接口并返回 JSON 数据。首先,您需要安装 Django REST framework: ``` pip install djangorestframework ``` 然后,在 Django 项目的 `settings.py` 文件添加 `'rest_framework'` 到 `INSTALLED_APPS` 列表。 接下来,您需要在 Django 创建一个视图,这个视图将返回 JSON 数据。您可以使用 Django REST framework 提供的 `APIView` 或 `GenericAPIView`: ```python from rest_framework.views import APIView from rest_framework.response import Response class MyView(APIView): def get(self, request, format=None): data = {'message': 'Hello, World!'} return Response(data) ``` 最后,您需要在 Django 的 URL 配置为这个视图添加一个 URL 模式: ```python from django.urls import path from .views import MyView urlpatterns = [ path('api/hello/', MyView.as_view(), name='hello'), ] ``` 在 Vue ,您可以使用 Axios 库发送 AJAX 请求: ```javascript import axios from 'axios'; axios.get('/api/hello/') .then(response => { console.log(response.data); }); ``` 这样,您就可以使用 Django 编写接口并返回 JSON 数据,并使用 Vue 发送 AJAX 请求。 ### 回答2: 使用Django编写接口返回JSON数据非常简单。首先,在Django项目创建一个视图函数,该函数处理来自前端请求数据,并返回一个JSON格式的响应。以下是一个简单的示例: ```python from django.http import JsonResponse def my_view(request): data = {'message': 'Hello, world!'} return JsonResponse(data) ``` 在这个例子,`my_view`视图函数会返回一个包含"message"键和"Hello, world!"值的JSON响应。 在前端使用Vue发送Ajax的Promise请求也很简单。你可以使用Vue的axios库来发送HTTP请求,并返回一个Promise对象以处理异步操作。以下是一个简单的示例: ```javascript import axios from 'axios'; axios.get('/api/my_view/') .then(response => { console.log(response.data.message); }) .catch(error => { console.error(error); }); ``` 在这个例子,我们使用axios的`get`方法发送一个GET请求到`/api/my_view/`接口。当Promise成功时,我们打印出接口返回数据的"message"键值对;当Promise失败时,我们打印出错误信息。 需要注意的是,你需要将前端的Vue项目与后端的Django项目连接起来,以确保请求能够正确地发送到后端接口。在Django项目的配置文件,可以设置`CORS_ORIGIN_ALLOW_ALL = True`来允许来自任何域的请求。 ### 回答3: 使用Django编写接口返回JSON数据很简单。首先,在Django项目创建一个视图函数,该函数将处理Ajax请求返回JSON数据。然后,使用Django的内置JSONResponse类将数据转换为JSON格式,并返回给前端。下面是一个示例: ```python from django.http import JsonResponse def get_data(request): # 处理数据的逻辑 data = { "name": "John", "age": 25, "city": "New York" } return JsonResponse(data) ``` 在上面的示例,我们定义了一个`get_data`视图函数,它返回一个包含姓名、年龄和城市的JSON数据使用Django的`JsonResponse`类将数据转换为JSON格式,并返回给前端。 现在,通过Vue发送Ajax的Promise请求,可以使用Axios库来简化操作。首先,确保在Vue项目安装了Axios。然后在Vue组件使用Axios发送请求,并使用Promise来处理响应数据。下面是一个示例: ```javascript import axios from 'axios'; // 发送请求的函数 function getData() { return axios.get('/api/get_data/') .then(response => { return response.data; }) .catch(error => { console.log(error); }); } // 在Vue组件调用函数 export default { data() { return { myData: {} } }, methods: { fetchData() { getData() .then(data => { this.myData = data; }); } }, created() { this.fetchData(); } } ``` 在上面的示例,我们首先导入Axios库并定义一个发送请求的函数`getData`。然后,在Vue组件使用该函数来获取数据,并存储在组件的`myData`属性。最后,在组件的`created`生命周期钩子调用`fetchData`函数来获取数据。 这样,我们就可以使用Django编写一个返回JSON数据的接口,并使用Vue发送Ajax的Promise请求来获取和处理这些数据

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值