简体   繁体   English

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

[英]Django - How do I properly send a list from template to AJAX to view?

I'm trying to make an AJAX get request to the server whenever a user clicks a button. 每当用户单击按钮时,我都试图向服务器发出AJAX获取请求。 There's two kinds of buttons. 有两种按钮。 One button to trigger all sirens for all the listed cameras, and there's a button for each individual camera. 一个按钮可触发所有列出的摄像机的所有警报,每个单独的摄像机都有一个按钮。

My problem is that I'm trying to return a list of dictionaries from AJAX to the view. 我的问题是我试图将AJAX的词典列表返回到视图。 JQuery sees the object as a string, so technically I guess it's already in a JSON format. jQuery将对象视为字符串,因此从技术上讲,我猜它已经是JSON格式。 When I send it to the view the view sees it as a Querydict and when I try to index it, it only returns singular characters of the string. 当我将其发送到视图时,视图将其视为Querydict,而当我尝试对其进行索引时,它仅返回字符串的单数字符。 When I try to call json.loads(cameras) in views.py , it throws an error saying: 当我尝试在views.py调用json.loads(cameras)时,抛出一个错误:

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 2)``` json.decoder.JSONDecodeError:期望属性名称用双引号引起来:第1行第3列(字符2)`

I know this is probably an issue with how I'm handling the variable on the front end side, but I'm not sure how to fix this issue. 我知道这可能与前端处理变量有关,但是我不确定如何解决此问题。 Should I initially pass the variable from the view to the template differently? 我最初是否应该将变量从视图传递到模板? Am I passing the variable from template to JQuery incorrectly? 我是否将变量从模板正确传递给JQuery? Am I handling the variable in JQuery incorrectly? 我在JQuery中处理变量不正确吗? Or am I just doing something wrong in the view? 还是我只是在做一些错误的看法?

Here is what the user sees 这是用户看到的

用户界面


views.py 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 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 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)
    }
  });

}

EDIT As per Daniel's comment, I've added the code in my views.py that passes the data to the template. 编辑根据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)

Here's what worked for me. 这对我有用。 My issue was that the camerasToTrigger string in Javascript had single quote characters ' , and these need to be double quotes " in order for the string to be converted to JSON. 我的问题是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)
    }
  });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过ajax从Django模板向视图发送值? - How to send values via ajax from django template to views? 如何从列表视图模板传递数据以使用angular来编辑视图模板 - How do I pass data from the list view template to edit view template using angular 将项目从 django 模板中的 forloop 填充数据通过 ajax 发送到 django 视图 - Send items from forloop populated data in django template through ajax to django view 如何在 Django 中连续将数据从视图发送到模板 - How to send data from view to template continously in Django C# Leaflet 如何使用 ajax 将数据从视图正确发布到控制器? - C# Leaflet how do i properly post data from view to controller using ajax? 如何从 JavaScript ajax 调用和打印来自 Django 模板中视图的返回数据 - How can I send localstorage data from JavaScript ajax call and print return data from views in Django template 将 json 从模板发送到 django 视图,然后重定向到该视图 - send json from template to django view and then redirect to that view 如何在 Django 模板上传递 Python 列表并在 JavaScript 中使用它? - How do I pass Python list on Django template and use it in JavaScript? 如何将 django object 列表发送到 javascript? - How do I send django object list to javascript? 如何使用 django 中的 Jquery、Ajax 将模板值发送到数据库? - How can i send my template values to database using Jquery, Ajax in django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM