简体   繁体   中英

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. 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. JQuery sees the object as a string, so technically I guess it's already in a JSON format. 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. When I try to call json.loads(cameras) in views.py , it throws an error saying:

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 3 (char 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? Am I handling the variable in JQuery incorrectly? Or am I just doing something wrong in the view?

Here is what the user sees

用户界面


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)
    }
  });

}

EDIT As per Daniel's comment, I've added the code in my views.py that passes the data to the template.

# 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.

# 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)
    }
  });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM