简体   繁体   中英

Cleaner way to pass multiple variables in javascript

I am passing the following variables in a json structure to my backend:

<a href="#;" class="match-item"

   data-reviewqueueid="{{ item.pk }}"
   data-useremail="{{ user.email}}"
   data-instanceid="{{ item.item_id }}"
   data-tracktitleid="{{ item.tracktitle_id }}"

   data-contenttype="{{ search_item.content_type_id }}"
   data-titleimdbid="{{ search_item.imdb_id }}"
   data-tvseriesimdbid="{{ search_item.imdb_series_id|default:'' }}"
   data-titlename="{{ search_item.name }}"
   data-titlereleaseyear="{{ search_item.release_year }}"
   data-ispartoftitle=""
   data-shouldbetvseries=""
   data-matchedfromimdb="{% if search_item.imdb_id and search_item.content_type_id != 'TV Series' %}true{% else %}{% endif %}"
   data-tvseriesname="{{ search_item.imdb_series.name }}"
   data-collectionepisodenumber=""
   data-collectionseasonnumber=""
   data-tvseriesreleaseyear=""
   data-collectionname="">
    Match
</a>

And in the javascript:

var data = new Object();

data.TVSeriesReleaseYear = $(this).data('tvseriesreleaseyear') || null;
data.CollectionName = $(this).data('collectionname') || null;
# ... etc ...
var jsonData = JSON.stringify(data)

$.post('{% url submit %}', jsonData, function () {
    ...
});

Each "item" is a search result object. Is there a clearer way to pass this data to the backend, or is this the suggested way?

You can use data() with no arguments to get all data attributes combined as one object

 console.log($('a.match-item').data())
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#;" class="match-item" data-reviewqueueid="1" data-useremail="foo@bar.com" data-instanceid="2" data-tracktitleid="3" data-null="null" data-true="true" > Match </a>

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