简体   繁体   中英

How can I set variable in php and use it in javascript

I made a function that is supposed to download html with all javascript results, but I am having a little problem, because I don'n know how I can send the url I am working with to the javascript function. The files look like this:

PHP Function:

public function getHTML($url) {
    $script_direction = str_replace('\classes', '', dirname(__FILE__)) . '\phantomjs\phantomjs.js';
    $row = array();
    exec(str_replace('\classes', '', dirname(__FILE__)) . '\phantomjs\phantomjs ' . $script_direction, $row);
    $html = implode('', $row);
    return $html;
}

Javascript:

var webPage = require('webpage');
var page = webPage.create();

page.open(url, function(status) {
    console.log(page.content);
    phantom.exit();
});

I need to the $url variable and send it to the javascript file and store it as url variable there.

You pass a variable between php and JS like this:

<?php
$url = "http://www.yoursite.com";
?>

<script>
var url = <?=json_encode($url)?>;
<script>

As commented by @ceejayoz, using json_encode() will ensure the a single quote ' in PHP doesn't break the JS.

You can echo the variable on the page with PHP to a javascript variable like this:

<script>
    var url = <?php echo json_encode($url); ?>
</script>

Your PHP variables are not directly accessible through JS

EDIT: Added json_encode per @ceejayoz comment.

I usually put the url in data attribute on the html view, for example:

<div id="mydiv" data-url="<?=json_encode($url);?>">

And with javascript, jquery, etc... you can get it:

var url=$("#mydiv").data("url");

You Can Use Ajax For This . for example this code uses jquery get method:

server.php :

$url = 'someUrl';
if(isset($_GET)){
if($_GET['request']=='get_url'){
     echo $url;
   }
}

Javascript Code:

    $.get('server.php',{request : 'get_url'},function(data){
    var url = data;
    });

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