通过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)

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>

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.

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 ;)