JQuery parseJSON from HTML not working

I get an error when trying to parse JSON from an HTML data attribute. This divI want to parse JSON from:

echo '<div class="udropdown" data-elements=\'{"option1" : "1", "option2" : "2" }\'></div>';

and this is part of jQuery (it is pushed, so $(this)necessary)

var ele = jQuery.parseJSON($(this).data('elements'));

but I keep getting this error:

Untrained SyntaxError: Unexpected Token o

+4
source share
3 answers

From documentation tojQuery.data :

data ( '{') ( '['), jQuery.parseJSON ; JSON, . JavaScript, .

$(this).data('elements') JSON .

jQuery.parseJSON(object) jQuery.parseJSON(object.toString()), jQuery.parseJSON("[object Object").

parseJSON. jQuery .

+3

, . parseJSON , , , :

[object Object]

. , [ ( - JSON), o - , , , ', " {.

$(this).data('elements') - .

:

JSON.parse({})

.

+1

$(this).data('elements')returns an object, so you do not need to parse anything, just use the returned one ele, for example:

$('.udropdown').click(function(){
    var ele = $(this).data('elements');
    console.log(ele.option1, ele.option2);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="udropdown" data-elements='{"option1" : "1", "option2" : "2" }'>Click HERE</div>
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1614940/


All Articles