[英]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. 我做了一个应该下载包含所有javascript结果的html的函数,但是我遇到了一个小问题,因为我不知道如何将正在使用的url发送到javascript函数。 The files look like this:
这些文件如下所示:
PHP Function: PHP功能:
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: 使用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. 我需要$ url变量并将其发送到javascript文件并将其存储为url变量。
You pass a variable between php and JS like this: 您可以在php和JS之间传递一个变量,如下所示:
<?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. 正如@ceejayoz所评论的那样,使用
json_encode()
将确保PHP中的单引号'
不会破坏JS。
You can echo the variable on the page with PHP to a javascript variable like this: 您可以使用PHP将页面上的变量回显为javascript变量,如下所示:
<script>
var url = <?php echo json_encode($url); ?>
</script>
Your PHP variables are not directly accessible through JS 您的PHP变量不能通过JS直接访问
EDIT: Added json_encode per @ceejayoz comment. 编辑:每个@ceejayoz评论添加了json_encode。
I usually put the url in data attribute on the html view, for example: 我通常将url放在html视图的data属性中,例如:
<div id="mydiv" data-url="<?=json_encode($url);?>">
And with javascript, jquery, etc... you can get it: 并使用javascript,jquery等...,您可以获得:
var url=$("#mydiv").data("url");
You Can Use Ajax For This . 您可以为此使用Ajax。 for example this code uses jquery get method:
例如,此代码使用jquery get方法:
server.php : server.php:
$url = 'someUrl';
if(isset($_GET)){
if($_GET['request']=='get_url'){
echo $url;
}
}
Javascript Code: JavaScript代码:
$.get('server.php',{request : 'get_url'},function(data){
var url = data;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.