IT story

HTML jQuery의 데이터 속성에 JSON 객체 저장

hot-time 2020. 7. 11. 09:32
반응형

HTML jQuery의 데이터 속성에 JSON 객체 저장


data-접근 방식을 사용하여 HTML 태그에 데이터를 저장 하고 있습니다.

<td><"button class='delete' data-imagename='"+results[i].name+"'>Delete"</button></td>

그런 다음 콜백에서 데이터를 다음과 같이 검색합니다.

$(this).data('imagename');

잘 작동합니다. 내가 붙어있는 것은 객체의 속성 중 하나 대신 객체를 저장하려고합니다. 나는 이것을 시도했다 :

<td><button class='delete' data-image='"+results[i]+"'>Delete</button></td>

그런 다음 이름 속성에 다음과 같이 액세스하려고했습니다.

var imageObj = $(this).data('image');
console.log('Image name: '+imageObj.name);

로그가 알려줍니다 undefined. 따라서 data-속성에 간단한 문자열을 저장할 수 있지만 JSON 객체를 저장할 수없는 것 같습니다 ...

나는 운이 없이이 아이를 사용하려고했습니다.

<div data-foobar='{"foo":"bar"}'></div>

data-접근 방식을 사용하여 HTML 태그에 실제 객체를 저장하는 방법에 대한 아이디어가 있습니까?


텍스트에 포함시키는 대신 $('#myElement').data('key',jsonObject);

실제로는 html에 저장되지 않지만 jquery.data를 사용하는 경우 모든 것이 추상화됩니다.

JSON을 다시 가져 오려면 구문 분석하지 마십시오 .

var getBackMyJSON = $('#myElement').data('key');

당신이 얻는 경우 [Object Object]대신 직접 JSON의 데이터 만 키하여 JSON에 액세스 :

var getBackMyJSON = $('#myElement').data('key').key;

실제로 마지막 예 :

<div data-foobar='{"foo":"bar"}'></div>

잘 작동하는 것 같습니다 ( http://jsfiddle.net/GlauberRocha/Q6kKU/ 참조 ).

좋은 점은 data-attribute의 문자열이 자동으로 JavaScript 객체로 변환된다는 것입니다. 나는이 접근법에서 반대로 단점을 보지 못합니다! 객체 속성을 통해 JavaScript에서 사용할 수 있도록 전체 데이터 세트를 저장하기에 하나의 속성으로 충분합니다.

(참고 : 데이터 속성에 String 대신 자동으로 Object 유형이 제공되도록하려면 특히 키 이름을 큰 따옴표로 묶으려면 유효한 JSON을 작성해야합니다.)


이것이 나를 위해 일한 방법입니다.

목적

var my_object ={"Super Hero":["Iron Man", "Super Man"]};

세트

encodeURIComponent ()문자열 화 된 객체를 인코딩하고 속성으로 설정하십시오.

var data_str = encodeURIComponent(JSON.stringify(my_object));
$("div#mydiv").attr("data-hero",data-str);

가져 오기

값을 객체로 가져 오려면 decodeURIComponent () 속성 값으로 디코딩 된 값을 구문 분석하십시오 .

var data_str = $("div#mydiv").attr("data-hero");
var my_object = JSON.parse(decodeURIComponent(data_str));

나를 위해 템플릿에 저장해야 하므로 그렇게 작동합니다 ...

// Generate HTML
var gridHtml = '<div data-dataObj=\''+JSON.stringify(dataObj).replace(/'/g, "\\'");+'\'></div>';

// Later
var dataObj = $('div').data('dataObj'); // jQuery automatically unescape it

직렬화 된 문자열base64 로 변환하면 직렬화 된 데이터 저장과 관련된 많은 문제를 해결할 수 있습니다 .

base64 문자열은 번거 로움없이 어디에서나 사용할 수 있습니다.

보세요:

WindowOrWorkerGlobalScope.btoa()메소드는 문자열의 각 문자가 2 진 데이터의 바이트로 처리되는 String 오브젝트에서 base-64로 인코딩 된 ASCII 문자열을 작성합니다.

WindowOrWorkerGlobalScope.atob()함수 는 base-64 인코딩을 사용하여 인코딩 된 데이터 문자열을 디코딩 합니다.

필요에 따라 변환합니다.


나를위한 비결은 키와 값 주위에 큰 따옴표추가 하는 것이 었습니다 . json_encode와 같은 PHP 함수를 사용하면 json으로 인코딩 된 문자열과 올바른 인코딩 방법을 알 수 있습니다.

문자열이 json으로 올바르게 인코딩 된 경우 jQuery ( '# elm-id'). data ( 'datakey') 는 문자열의 객체를 반환합니다.

jQuery 설명서에 따라 : ( http://api.jquery.com/jquery.parsejson/ )

잘못된 JSON 문자열을 전달하면 JavaScript 예외가 발생합니다. 예를 들어, 다음은 모두 유효하지 않은 JSON 문자열입니다.

  1. "{test : 1}" (테스트에는 큰 따옴표가 없습니다).
  2. "{'test': 1}" ('test' is using single quotes instead of double quotes).
  3. "'test'" ('test' is using single quotes instead of double quotes).
  4. ".1" (a number must start with a digit; "0.1" would be valid).
  5. "undefined" (undefined cannot be represented in a JSON string; null, however, can be).
  6. "NaN" (NaN cannot be represented in a JSON string; direct representation of Infinity is also n

Using the documented jquery .data(obj) syntax allows you to store an object on the DOM element. Inspecting the element will not show the data- attribute because there is no key specified for the value of the object. However, data within the object can be referenced by key with .data("foo") or the entire object can be returned with .data().

So assuming you set up a loop and result[i] = { name: "image_name" } :

$('.delete')[i].data(results[i]); // => <button class="delete">Delete</delete>
$('.delete')[i].data('name'); // => "image_name"
$('.delete')[i].data(); // => { name: "image_name" }

For some reason, the accepted answer worked for me only if being used once on the page, but in my case I was trying to save data on many elements on the page and the data was somehow lost on all except the first element.

As an alternative, I ended up writing the data out to the dom and parsing it back in when needed. Perhaps it's less efficient, but worked well for my purpose because I'm really prototyping data and not writing this for production.

To save the data I used:

$('#myElement').attr('data-key', JSON.stringify(jsonObject));

To then read the data back is the same as the accepted answer, namely:

var getBackMyJSON = $('#myElement').data('key');

Doing it this way also made the data appear in the dom if I were to inspect the element with Chrome's debugger.


.data() works perfectly for most cases. The only time I had a problem was when the JSON string itself had a single quote. I could not find any easy way to get past this so resorted to this approach (am using Coldfusion as server language):

    <!DOCTYPE html>
        <html>
            <head>
                <title>
                    Special Chars in Data Attribute
                </title>
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
                <script>
                    $(function(){
                        var o = $("##xxx");
                        /**
                            1. get the data attribute as a string using attr()
                            2. unescape
                            3. convert unescaped string back to object
                            4. set the original data attribute to future calls get it as JSON.
                        */
                        o.data("xxx",jQuery.parseJSON(unescape(o.attr("data-xxx"))));
                        console.log(o.data("xxx")); // this is JSON object.
                    });
                </script>
                <title>
                    Title of the document
                </title>
            </head>
            <body>
                <cfset str = {name:"o'reilly's stuff",code:1}>
<!-- urlencode is a CF function to UTF8 the string, serializeJSON converts object to strin -->
                <div id="xxx" data-xxx='#urlencodedformat(serializejson(str))#'>
                </div>
            </body>
        </html>

For the record, I found the following code works. It enables you to retrieve the array from the data tag, push a new element on, and store it back in the data tag in the correct JSON format. The same code can therefore be used again to add further elements to the array if desired. I found that $('#my-data-div').attr('data-namesarray', names_string); correctly stores the array, but $('#my-data-div').data('namesarray', names_string); doesn't work.

<div id="my-data-div" data-namesarray='[]'></div>

var names_array = $('#my-data-div').data('namesarray');
names_array.push("Baz Smith");
var names_string = JSON.stringify(names_array);
$('#my-data-div').attr('data-namesarray', names_string);

!DOCTYPE html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$("#btn1").click(function()
{
person = new Object();
person.name = "vishal";
person.age =20;
    $("div").data(person);
});
  $("#btn2").click(function()
{
    alert($("div").data("name"));
});

});

</script>
<body>
<button id="btn1">Attach data to div element</button><br>
<button id="btn2">Get data attached to div element</button>
<div></div>
</body>


</html>

Anser:-Attach data to selected elements using an object with name/value pairs.
GET value using object propetis like name,age etc...

This code is working fine for me.

Encode data with btoa

let data_str = btoa(JSON.stringify(jsonData));
$("#target_id").attr('data-json', data_str);

And then decode it with atob

let tourData = $(this).data("json");
tourData = atob(tourData);

참고URL : https://stackoverflow.com/questions/8542746/store-json-object-in-data-attribute-in-html-jquery

반응형