Django-jQuery coupling: How to get date from server-side to JS?
I have a page which uses jQuery for some AJAX-stuff und Django as main application server. Let's say I have some link where I want to attach a 'click' handler, to display a jQuery Dialog where the content of the dialog is loaded via AJAX from the server. The server needs some kind of ID to generate the dialog content. This is is available in the original site-template and should pe passed to the server using JS. What would be the most correct (or "best practice") way to store the mentioned ID in the page:
Methods
Create a link and attache a "click" handler that does
preventDefault()
and use the href of the link in JS. I.e.:<a id="do-dialog" hr开发者_运维知识库ef="{% url app.views.some_view param=object.id %}">Show me!</a>
and a JS that looks like this:$("#do-dialog").click(function (e) { var url = $(this).attr("href"); /* do ajax with url */ e.preventDefault(); });
Encode the ID in a class or id attribute of the link. I.e:
<a class="do-dialog object-{{ object.id }}" href="#">Show me!</a>
and use some JS to get the ID from the class and use this.Violate HTML and put the ID in an custom attribute and fetch it from there:
<a obj-id="{{ object.id }" class="do-dialog" href="#">Show me!</a>
Pros and Cons
Looks like the most "valid" way to do this. The data is stored in a known attribute and can be used directly from JS. However, if the user has turned JS off, the user will be taken to a page that return JSON or XML. (Note: for this particular site it is totally okay to not work with JS is turned off!)
Doesn't have this disatvantage. With JS turned off, nothing will happen. However, you have to parse the id from the class-attribute, which looks a little bit ugly and error prone to me.
Is no valid HTML. On the other hand you have the needed data directly available.
Approach number 1 makes the most sense. You are actually embedding the data where its going to be used and its valid HTML. You could also put the data in a hidden element of a form. Or if you are using HTML5 you could use the new data- attributes.
精彩评论