如何在客户端的javascript /中访问Django返回的json对象?

我很难找到一种方法来在客户端使用Django返回的数据。我想我在这里混淆了几个概念。

This is my view that calls the model StocksPrice and returns all data in the table column stockName:

def getStocksAvailable(request, *args, **kwargs):
    StocksAvailable = serializers.serialize('json', StocksPrice.objects.values(stockName))
    return HttpResponse({"data": StocksAvailable})

并根据Javascript部分进行测试:

var received_data = "{{ StocksAvailable }}"
    console.log(received_data);

# Outputs: {{ StocksAvailable }}

I also tried it using render in the view:

def getStocksAvailable(request, *args, **kwargs):
    StocksAvailable = serializers.serialize('json', StocksPrice.objects.values(stockName))
    return render({"data": StocksAvailable})

为什么JS为什么将其记录为字符串,而它应该是包含返回的json对象的变量?我基本上如何从视图中打印返回的数据以进行调试(也许json本身是错误的)?

更新版本@Willems回复

网址映射:

urlpatterns = [

    path('terminal/getStocksAvailable/', get_stocks_available),
]

视图

def get_stocks_available(request, *args, **kwargs):
    stocks_available = serializers.serialize('json', StocksPrice.objects.values(stockName))
    return JsonResponse({'data': json.loads(stocks_available)})

模型

class StocksPrice(models.Model):
    stockName = models.CharField(max_length=100, blank=False)
     [...]

    class Meta:
        db_table = 'StocksPrice'

JS

$( document ).ready(function() {
    $.ajax('getStocksAvailable/', {
        method: 'GET',
        async: "True",
        dataType: "json",
        success: function () {
            var received_data = "{{stocks_available}}"
            console.log(received_data);
        }
    })
});

现在抛出:

Traceback (most recent call last):
  File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Jonas\Desktop\CFD\CFD\terminal\views.py", line 10, in get_stocks_available
    stocks_available = serializers.serialize('json', StocksPrice.objects.values(stockName))
NameError: name 'stockName' is not defined
[17/May/2020 14:36:56] "GET /terminal/getStocksAvailable/ HTTP/1.1" 500 16181
[17/May/2020 14:36:56] "GET /terminal/getStocksAvailable/ HTTP/1.1" 500 16181

评论
  • 圣杰
    圣杰 回复
    为什么JS为什么将其记录为字符串,而它应该是包含返回的json对象的变量?

    Because serializers.serialize(..) returns a string. If you want to wrap it in an object, you can for example decode it:

    import json
    from django.http import JsonResponse
    
    def get_stocks_available(request, *args, **kwargs):
        stocks_available = serializers.serialize('json', StocksPrice.objects.values(stockName))
        return JsonResponse({'data': json.loads(stocks_available)})