Note: using the Laravel framework but the concept shouldn't be too different.

How would I go about passing my $data['method'] and $data['id] to javascript?

<div id="player" data-method="{{ $data['method'] }}" data-id="{{ $data['id'] }}"></div>

Data method and Data id are passed through a controller.

In javascript I've currently got

var method = "<?php echo $data-id[]>";
var id = "<?php echo $data-method[]>";

Which obviously don't work

有帮助吗?

解决方案

To get the method:

var method = document.getElementById("player").getAttribute("data-method");

And to get the id:

var id = document.getElementById("player").getAttribute("data-id");

其他提示

In addition to @chris97ong answer, if you use jQuery, then you can use such constructions:

var method = $('#player').data('method');
var id = $('#player').data('id');

But if you want to paste id and method values directly to javascript, then use:

var method = "<?php echo $data['id']>";
var id = "<?php echo $data['method']>";

Exactly like in your own way.

You can pass array as

<?php
    $array = array("a","b","c","d");
    $json_str = json_encode($array);
?>
<a str='<?php echo $json_str; ?>' class="array_pass">Pass Value</a>

<script>
$(document).ready(function(e) {
    $(".array_pass").click(function() {
        var str = $(this).attr("str");
        var array = jQuery.parseJSON(str);
        alert(array[0]);
    });
});
</script>

Jeffrey Way provides a nice plugin to pass variables to JavaScript in your controller: https://github.com/laracasts/PHP-Vars-To-Js-Transformer

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top