开发者

How to store records id for data from ajax query in dynamicly created html elements

开发者 https://www.devze.com 2023-02-02 02:13 出处:网络
Assume this configuration: server-side is PHP application responding for requests with data (list of items, single item details, etc.) in json format

Assume this configuration:

  • server-side is PHP application responding for requests with data (list of items, single item details, etc.) in json format
  • client-side is JQuery application sending ajax request to that PHP app and creating html content corresponding with received data

For example: client requests "list o开发者_如何学Pythonf all animals with names staring with 'A'", gets the json response from server, and for every "animal" creates some html gizmo like div with animal description or something like that. It doesn't really matter what html element it will be but it has to point exactly to specific record by "containing" id of that record.

And here is my dilemma: is it good solution to use "id" property for that? So it would be like:

<div id="10" class="animal">
<p>
This is animal of very mysterious kind...
</p>
</div>

<div id="11" class="animal">
<p>
And this one is very common to our country...
</p>
</div>

where id="10" is of course indication that this is representation of record with id = 10.

Or maybe I should store this record id in some custom made tag like

<record_id>10</record_id> 

and leave an "id" strictly for what it was meant to be (css selector)?

I need that record id for further stuff like updating database with some user input or deleting some of "animals" or creating new ones or anything that will be needed. All manipulations will be done with JQuery and ajax requests and responses will be visualized also with dynamic creation of html interface.

I'm sure that somebody had to deal with that kind of stuff before so I would be grateful for some tips on that topic.


You can use the data() provided by jQuery API for this purpose.

To store data you can use

$("element").data("record-id", 5);

To retrieve the value you can use

$("element").data("record-id");

The data() stores the data in such a way that it is safe from any memory leak issues.

You can read more about data() method here.


You should use the data method to store arbitrary data on an element and then retrieve it. Example:

var elm = $('<li>').data('record_id', 5);

And retrieving simply by:

elm.data('record_id');
0

精彩评论

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