Django-如何正确地将模板列表发送到AJAX进行查看?

时间:2019-06-28 15:00:49

标签: javascript jquery json django ajax

每当用户单击按钮时,我都试图向服务器发出AJAX获取请求。有两种按钮。一个按钮可触发所有列出的摄像机的所有警报,每个单独的摄像机都有一个按钮。

我的问题是我试图将字典列表从AJAX返回到视图。 jQuery将对象视为字符串,因此从技术上讲,我猜它已经是JSON格式。当我将其发送到视图时,视图将其视为Querydict,而当我尝试对其进行索引时,它仅返回字符串的单数字符。当我尝试在json.loads(cameras)中调用views.py时,会引发错误消息:

  

json.decoder.JSONDecodeError:期望属性名称用双引号引起来:第1行第3列(字符2)`''

我知道这可能与前端处理变量有关,但是我不确定如何解决此问题。我最初是否应该将变量从视图传递到模板?我是否将变量从模板正确传递给JQuery?我在JQuery中处理变量不正确吗?还是我在视图中做错了什么?

这是用户看到的内容

User interface


views.py

def trigger_sirens(request):
    # Retrieve the list of dictionaries
    cameras = request.GET.get('cameras')
    print(type(cameras)) # ==> <class 'str'>
    print(cameras)       # ==> [{'name': 'camera1', 'site': 'city'}, {'name': 'camera2', 'site': 'city'}]
    print(cameras[0])    # ==> [

    # Manipulate data

    return JsonResponse({'success': True}, status = 200) # This is just a placeholder for now

siren_search.html

<!-- These buttons are wrapped in forms because this is how I built it first
without using javascript, but now I'm trying to implement javascript functionality -->

<!-- A button to trigger all the listed -->
<form id="trigger-all-form" action="{% url 'camera_search:siren_search' %}" method="GET">
    <button id="trigger-all-btn" name="pulse-all-sirens" type="submit"
        class="btn siren-btn btn-lg btn-block js-trigger-all-sirens-btn"
        value="{{ cameras }}">
        Trigger all sirens at {{ term }}
    </button>
</form>

<!-- A button to trigger only one siren -->
<form id="{{ camera.asset_name }}-siren-form"
    action="{% url 'camera_search:siren_search' %}" method="GET">
    <button type="submit" name="pulse-siren" id="{{ camera.asset_name }}-siren-btn"
        name="button-big-submit" class="btn siren-btn" value="{{ camera.asset_name }}">
        {{ camera.asset_name }}
    </button>
</form>

custom.js

function buttonAjaxCall(buttonObject) {
  var camerasToTrigger = buttonObject.attr('value');

  console.log(jQuery.type(camerasToTrigger))                 // string
  console.log(camerasToTrigger)                              // [{'name': 'camera1', 'site': 'city'}, {'name': 'camera2', 'site': 'city'}]
  console.log(jQuery.type(JSON.stringify(camerasToTrigger))) // string
  console.log(JSON.stringify(camerasToTrigger))              // "[{'name': 'camera1', 'site': 'city'}, {'name': 'camera2', 'site': 'city'}]"

  if (buttonObject.hasClass('js-trigger-all-sirens-btn')) {
    // Convert data this way, still not sure how
  }
  else {
    // Convert data for one button, still not sure how
  }

  $.ajax({
    url: 'siren/',
    type: 'GET',
    data: {
      'cameras': camerasToTrigger,
    },
    dataType: 'json',
    success: function (response) {
      console.log('Success: ', response)
    },
    error: function (response) {
      console.log('Error: ', response)
    }
  });

}

编辑 根据Daniel的评论,我已在views.py中添加了将数据传递到模板的代码。

# deployed is a list of dictionaries
context = {
    'cameras': sorted(deployed, key=lambda camera: (camera['site_id'] == 'N/A', camera['site_id'])),
    'term': term
}

return render(request, 'siren_search.html', context)

1 个答案:

答案 0 :(得分:0)

这对我有用。我的问题是Javascript中的cameraToTrigger字符串具有单引号字符',并且这些字符必须是双引号"才能将字符串转换为JSON。

# views.py

def trigger_sirens(request):

    # Retrieve the list of dictionaries in JSON format
    cameras = request.POST.get('cameras', None)

    # Read in the JSON object if it exists
    if cameras_json is not None:
        cameras = json.loads(cameras_json)
    else:
        return JsonResponse({'success': False}, status = 400)

    return JsonResponse({'success': True}, status = 200)
// custom.js

function buttonAjaxCall(buttonObject) {
  var camerasToTrigger = buttonObject.attr('value');
  var data = {
    // Make sure the list is JSON
    'cameras': camerasToTrigger.replace(/'/g, '"');
  }

  $.ajax({
    url: 'siren/',
    type: 'GET',
    data: data,
    dataType: 'json',
    success: function (response) {
      console.log('Success: ', response)
    },
    error: function (response) {
      console.log('Error: ', response)
    }
  });

}