Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery data-options truncates when the value is a French name

I have a div in my html,

<div id="datadiv"></div>

In my script i update the div(datadiv) by sending a request to my server.

<script>

  $.ajax({
  url: 'getusers.do',
  dataType: 'html',
  success: function( data ) {
      $("#datadiv").html(data);
      console.log($("#namespan").data("options").name); //undefined 
  }
  })

</script>

Java Code:

StringBuffer sb = new StringBuffer();
String username = "";

// The below code runs in a for loop. I have many usernames.
username = "François L'Écuyer"; // This is a French name. 
sb.append("<span id=\"namespan\" data-options='{\"name\":\""+username+"\"}'>"+username+"</span>");
//Loop ends

return sb.toString(); //This value is returned to the ajax success.

When i get the name which is stored in the data. I get undefined. The data-options gets truncated and broken.

like image 451
Jeevi Avatar asked Feb 03 '26 18:02

Jeevi


1 Answers

Let jquery handle it. Try constructing the element using jquery instead of constructing as a string:

var username = "François L'Écuyer";
var temp_data = $('<span/>', {'id': 'namespan', 
                            'data-options' : '{"name":"'+username+'"}',
                            'text':'UserName'});
$("#datadiv").html(temp_data);

Demo

or stringify the object

var data = { name: username } ;
var temp_data = $('<span/>', {
    'id': 'namespan',
    'text': 'UserName',
    'data-options': JSON.stringify(data)
});

$("#datadiv").html(temp_data);

Demo

Update

Proper encoding to add on proper escaping should make it right. instead of using \" to wrap the data attribute value JSON's key/value use &quot; and try something like:

'<span id="namespan" data-options="{&quot;name&quot;:&quot;'+username+'&quot;}">UserName</span>'

or probably in java:

"<span id=\"namespan\" data-options=\"{&quot;name&quot;:&quot;"+username+"&quot;}\">"+username+"</span>"

Demo

like image 82
PSL Avatar answered Feb 05 '26 07:02

PSL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!