[英]How can I access a Django returned json object in javascript / on the client-side?
I'm having hard times to find a way to use my Django returned data on the clientside.我很难找到一种方法来使用我的 Django 在客户端返回的数据。 I think I mix up several concepts here.
我想我在这里混淆了几个概念。
This is my view that calls the model StocksPrice
and returns all data in the table column stockName
:这是我调用 model
StocksPrice
并返回表列stockName
中的所有数据的视图:
def getStocksAvailable(request, *args, **kwargs):
StocksAvailable = serializers.serialize('json', StocksPrice.objects.values(stockName))
return HttpResponse({"data": StocksAvailable})
and according Javascript part for testing purposes:并根据 Javascript 零件进行测试:
var received_data = "{{ StocksAvailable }}"
console.log(received_data);
# Outputs: {{ StocksAvailable }}
I also tried it using render
in the view:我还尝试在视图中使用
render
:
def getStocksAvailable(request, *args, **kwargs):
StocksAvailable = serializers.serialize('json', StocksPrice.objects.values(stockName))
return render({"data": StocksAvailable})
Why does JS logs it as a string whereas it is supposed to be a variable containing the returned json object?为什么 JS 将它记录为字符串,而它应该是包含返回的 json object 的变量? And how could I basically print the returned data from the view for debugging (maybe s.th. is wrong with the json itself)?
我怎么能基本上从视图中打印返回的数据以进行调试(也许json本身有问题)?
Url mapping: Url 映射:
urlpatterns = [
path('terminal/getStocksAvailable/', get_stocks_available),
]
View看法
def get_stocks_available(request, *args, **kwargs):
stocks_available = serializers.serialize('json', StocksPrice.objects.values(stockName))
return JsonResponse({'data': json.loads(stocks_available)})
Model Model
class StocksPrice(models.Model):
stockName = models.CharField(max_length=100, blank=False)
[...]
class Meta:
db_table = 'StocksPrice'
JS JS
$( document ).ready(function() {
$.ajax('getStocksAvailable/', {
method: 'GET',
async: "True",
dataType: "json",
success: function () {
var received_data = "{{stocks_available}}"
console.log(received_data);
}
})
});
which now throws:现在抛出:
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
Why does JS logs it as a string whereas it is supposed to be a variable containing the returned json object?
为什么 JS 将它记录为字符串,而它应该是包含返回的 json object 的变量?
Because serializers.serialize(..)
returns a string .因为
serializers.serialize(..)
返回一个 string 。 If you want to wrap it in an object, you can for example decode it:如果您想将其包装在 object 中,您可以例如对其进行解码:
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
)}
)
EDIT1:编辑1:
You furthermore need to pass a value for stockName
, and process the result.view_data
(this is a parameter in the data):您还需要为
stockName
传递一个值,并处理result.view_data
(这是数据中的一个参数):
$( document ).ready(function() {
$.ajax('getStocksAvailable/
?stockName=???', {
method: 'GET',
async: "True",
dataType: "json",
success: function (result) {
var received_data =
result.view_data;
console.log(received_data);
}
})
});
with ???
与
???
to fill in.填写。
in the view, you can then access request.GET
to obtain the value for stockName
:在视图中,您可以访问
request.GET
以获取stockName
的值:
import json
from django.http import JsonResponse
def get_stocks_available(request, *args, **kwargs):
stockName =
request.GET['stockName']
stocks_available = serializers.serialize('json', StocksPrice.objects.values(stockName))
return JsonResponse({'data': json.loads(stocks_available)})
EDIT2:编辑2:
If you want to use values from a column named stockName
, then you should use:如果要使用名为
stockName
的列中的值,则应使用:
import json
from django.http import JsonResponse
def get_stocks_available(request, *args, **kwars):
stocks_available = serializers.serialize('json', StocksPrice.objects.values(
'stockName'))
return JsonResponse({'data': json.loads(stocks_available)})
and at the JavaScript side:在 JavaScript 一侧:
$( document ).ready(function() {
$.ajax('getStocksAvailable/', {
method: 'GET',
async: "True",
dataType: "json",
success: function (result) {
var received_data =
result.view_data;
console.log(received_data);
}
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.