douniuta4783
2011-12-24 17:12 阅读 178

通过HTML文件将参数从服务器端传递到Javascript

How do I pass parameters from a HTML file to a external Javascript file if these parameters are provided to the HTML by the server side (Codeigniter controller)?

In other words, I have parameters that I want to pass from the serverside PHP/Codeigniter to the Javascript file.

PHP/Codeigniter Serverside Code

function view($id) {

    $data['id'] = $id;    // this is the variable I want to pass to Javascript

    $this->load->view('index', $data);

}

HTML

<html>
    <head>
        <script type="text/javascript" src="./js/targetfile.js"></script>
    </head>
    <body>
        <?php echo $id; ?> //this is how I can retrieve the variable from serverside
...

Javascript (targetfile.js)

var id = id_from_serverside;  // This is where I want the serverside $id to go

Additional Info:

The variable $id is grabbed off the url, so for http://www.domain.com/view/1234, serverside variable $id will be set the value 1234. This 1234 value will then have to be passed to the javascript file (which does an AJAX call back to the serverside to retrieve data from the database)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    douao1959 douao1959 2011-12-24 17:30

    You should be able to just do this:

    <script type="text/javascript>
    var id = <?php echo $id; ?> //this is how I can retrieve the variable from serverside
    </script>
    <script type="text/javascript" src="./js/targetfile.js"></script>
    
    点赞 评论 复制链接分享
  • dtfo55908 dtfo55908 2011-12-24 17:18

    How about this:

    HTML

    <html>
        <head>
            <script type="text/javascript" src="./js/targetfile.js"></script>
        </head>
        <body>
            <input type="hidden" id="my_id" value="<?= $id ?>" />
    ...
    

    JavaScript

    var id = $('#my_id').val();
    

    Try this:

    PHP/Codeigniter Serverside Code

    function view($id) {
        echo $id;
    }
    

    JavaScript

    $.get('/mycontroller/view', function(data) {
        alert(data);
    }, 'html');
    

    Skip the <html><head>... stuff. Just print the data you need. Then get the data via AJAX.

    点赞 评论 复制链接分享
  • duan4739 duan4739 2011-12-24 18:28

    You can send parameters as JSON objects:

    <?php 
        $object = array("foo" => "bar", 12 => true); 
        $encoded_object = json_encode($object); 
        echo '<script>var _page_params = '.$encoded_object.';</script>';
    ?> 
    

    will output something like this*:

    <script>var _page_params = {"foo": "bar", "12": "true"};</script>
    

    disclaimer: Don't have PHP on this machine, so there might be typos ;)

    点赞 评论 复制链接分享