简体   繁体   中英

AJAX response using HTML5 data attribute

I've a working env where I'm using AJAX response to fill in HTML elements.

for example AJAX response has two(or n) objects like this:

0:Object
     id: "111"
     Name: "abc"
1:Object
     id: "112"
     Name: "xyz"

Then, There already would be two(or n) divs with user class and HTML5 data-user containing the id in HTML

<div class='user' data-user='111'>
    <div class='userId'data-userId='111> </div>
     <div class='usernm' data-user='usernm'> </div>
</div>

<div class='user' data-user='112'>
    <div class='userId'data-userId='112> </div>
     <div class='usernm' data-user='usernm'> </div>
</div>

What I need is put those response values in this divs like this:

<div class='user' data-user='111'>
    <div class='userId'data-userId='111> 111 </div>
     <div class='usernm' data-user='usernm'> abc </div>
</div>
 <div class='user' data-user='112'>
    <div class='userId'data-userId='112> 112 </div>
     <div class='usernm' data-user='usernm'> xyz </div>
</div>

What I'm currently doing (and is working) is using jQuery find (see below code) but now I'm suggested to put the responses using HTML5 data-.. attribute. I can't get around it, if someone can help up with it..

$.ajax({
    type: 'GET',
    url: '/url/goes/here',
    dataType: "json",
    success: function(data) {
       $('.user').each(function(key, value){ //i need to remove .user and use data-user here (if possible)
            $(value).find('.userid').text(data[key].id); //i need to put values using data attr instead of find
            $(value).find('.usernm').text(data[key].name); //i need to put values using data attr instead of find              
       });
    }
});

Data attributes are accessed by:

$(#id).data('userId');

or

$(#id).attr('data-userId');

and to set a value in that data attribute:

$(#id).data('userId', 'value');

or

$(#id).attr('data-userId', 'value');

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