Question

I trid to implement twitter-like message reply in Flask MiniTwit example, but now I can't make the 'reply' button for each message work, how?

<ul class=messages>
{% for message in messages %}
<li><img src="{{ g.get_user(message.author_id).email|gravatar(size=48)}}"><p>
<strong><a href="{{ url_for('user_timeline', username=message.author_id)
}}">{{ message.author_id }}</a></strong>
{{ message.text }}
<small>&mdash; {{ message.pub_date|datetimeformat }}</small>
{% if g.user %}
<script type=text/javascript>
 $(function () {
  messageid = $('a#reply').data('messageid');
  $('a#reply').bind('click', function () {
  $.getJSON($SCRIPT_ROOT + '/_get_replies', {
    messageid: $('#reply').data('messageid'),
    userid: $('#reply').data('userid')
  }, function (data) {
 $('div#' + messageid).text(data.result)
});
return false;
});
});
</script>
<p  align=right style='text-align:right'><small>
<a href=# data-userid="{{g.user._id}}" data-messageid="{{message._id}}" id="reply">
Reply
</a></small></p>
<p><div id="{{message._id}}">I TRY TO PUT REPLIES HERE!</div></p>
{% endif %}
{% else %}
<li><em>There's no message so far.</em>
{% endfor %}
</ul>

before click 'reply' button, My page is like:

before click 'reply' button

After click any of the 'reply' buttons, the page is like:

After click any of the 'reply' buttons

Was it helpful?

Solution

You are using text when you are returning HTML - the HTML is escaped, resulting in your issue - use html instead:

// Change
$('div#' + messageid).text(data.result)
// to
$('div#' + messageid).html(data.result)
                      ^^^^

A couple of other points to consider:

  1. Each ID should exist only once in the document. Having multiple links with the ID "reply" will result in issues later on. Leave it out entirely, or change it to a class.
  2. Use delegate (on if you are using jQuery 1.7 or greater) and bind just once to the root element (in your case ul.messages). This reduces the number of event handlers on the page to 1 - and will result in greatly increased performance with a large number of messages.
  3. Cache your selectors to improve performance even more - no need to go to the DOM 3 times when you have all of your information in the first pass.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top