开发者

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

  1. 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();
    });
    
  2. 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.

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

  1. 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!)

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜