douchuanghan1344 2015-05-29 06:25
浏览 19
已采纳

如何避免使用隐藏字段将数据从PHP传递到Javascript?

I am developping a website with some serious Javascript involved and I have to use generated data from PHP in my JS code.

For example, to be able to use my page ID in JS, I proceed like this:

<input type="hidden" id="pageId" value="<?php echo $page->getId() ?>" />
<button id="runJs">RUN</button>

And in my javascript (with jQuery):

$(function() {
  $('#runJs').click(function() {
    var id = $('#pageId').val();
  });
});

It works, but is there a cleaner way to do it?

  • 写回答

2条回答 默认 最新

  • duanao3204 2015-05-29 06:25
    关注

    Since HTML5, one can now add user-made attributes to any HTML tag as long as it starts with data-.

    In HTML5:

    <button id="runJs" data-pageId="<?php echo $page->getId() ?>">RUN</button>
    

    In JS:

    $(function() {
      $('#runJs').click(function() {
        var id = $(this).attr('data-pageId');
      });
    });
    

    Or, as said Eric Martinez in the comments, using jQuery:

    var id = $(this).data('pageId');
    

    Passing data this way is cleaner for two reasons:

    1. It is not using a side tag that could be confusing.
    2. The data you pass is included in the button, which means another button with its own data-XXX can use the same JS function, even on the same page.

    Example

    HTML:

    <button data-value="5">Square it!</button>
    <button data-value="7">Square it!</button>
    <button data-value="12">Square it!</button>
    

    JS:

    $(function() {
      $('button').click(function() {
        var value = $(this).attr('data-value');
        alert(value * value); // Shows 25, 49 or 144 depending of the button pressed.
      });
    });
    

    The function doesn't know the button. The buttons don't even need an ID as long as JS is involved.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?