简体   繁体   中英

Returning JavaScript through PHP - good or bad idea?

So I have a jQuery AJAX call that builds a profile when clicked. It would only be called once so I thought that I could just pop a script into the generated html instead of placing it inside the success AJAX call.

while($row = mysql_fetch_array($result)){
      $content .= '
          <div class="content cols-1 points">
            <h3>Points</h3>
            <span>
              <b class="points_1" data-points="'.$row['p_1'].'"></b> 
              <b class="points_2" data-points="'.$row['p_2'].'"></b>
              <b class="points_3" data-points="'.$row['p_3'].'"></b>
              <b class="points_4" data-points="'.$row['p_4'].'"></b>
            </span>
          </div>
        ';
}

$content.= '
    <script type="text/javascript">
      $(".points b").click(function(){
        setDots(this);
      })
    </script>
';

echo $content;

It feels cleaner, it only executes when I have the required html and I don't have as much JavaScript on page load... But is this bad practice?

Please explain any flaws if there is any. Thanks!

I don't see any particular flaws, besides the fact that the few lines of JS are returned with every AJAX response, which increases (very slightly) the size of the AJAX response, which in turn, given a lot of traffic, increases bandwith usage. That, and the fact that returning JS from AJAX is always frowned upon...

So I would write it in the page making the AJAX call using on event handler on document, like so:

$(document).on('click','.points b', function() { setDots(this) });

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