首页 > 解决方案 > 在Django中将ajax json替换为python json

问题描述

我正在尝试使用 Django 中的 json 将 Ajax json url 更改为 python 变量。如您所见,两种情况下的 url 都是相同的,所以我不明白发生了什么。提前致谢。

我在找什么但不起作用

<script>
$(document).ready(function() {
var table = $('#users').DataTable({
    "ajax": "{{ es_docs }}",

我的观点:

@login_required(login_url="/login/")
def index(request):
    context = {}
    context['segment'] = 'index'
    html_template = loader.get_template( 'index.html' )
    resp = requests.get("https://gyrocode.github.io/files/jquery-datatables/arrays_id.json").json()
    context['es_docs'] = resp
    return HttpResponse(html_template.render(context, request))

模板.html:

<script>
$(document).ready(function() {
var table = $('#users').DataTable({
    "ajax": "https://gyrocode.github.io/files/jquery-datatables/arrays_id.json",
    'columnDefs': [
        {
            'targets': 0,
            'checkboxes': {
            'selectRow': true
            }
        }
    ],
    'select': {
        'style': 'multi'
    },
    'order': [[1, 'asc']]
});

标签: pythondjango

解决方案


这个:

resp = requests.get(...)

返回一个response对象。要获取 json 数据,请执行以下操作:

response = requests.get(...)

if response.status_code != 200: 
    # handle errors:

else:
    json_data = response.json()

context['es_docs'] = json_data

推荐阅读