大家好我有一个PHP文件和这段代码:
<?php echo "Hello World"; ?>
<script type="text/javascript">
$(document).on('click', '.order-submit', function() {
dataName = $(this).data('name');
var company = <?php echo json_encode(get_Comp( /* dataName here */)); ?>;
});
</script>
如何传递javascript变量&#34; dataName&#34;到我的PHP功能&#34; get_Comp&#34;? 如果有人帮忙,我会很高兴。谢谢!
答案 0 :(得分:3)
这是不可能的,你需要使用ajax来实现这个目标:
PHP getcomp.php
<?php
//put here your get_Comp() function
$dataName = $_POST['dataName'];
echo json_encode(get_Comp($dataName));
?>
<强> JAVASCRIPT 强>
<?php echo "Hello World"; ?>
<script type="text/javascript">
$(document).on('click', '.order-submit', function() {
dataName = $(this).data('name');
var company;
$.post('getcomp.php', {dataName: dataName}, function(data) {
company = data; //company should be equal to json_encode(get_Comp($dataName));
});
});
</script>
答案 1 :(得分:0)
PHP代码在服务器端呈现,而JavaScript在客户端呈现。因此,您无法将JS变量传递给PHP函数。
您可以做的是,您可以使用dataName
向您的PHP服务器发出AJAX请求以获取信息。
答案 2 :(得分:0)
This is not possible for render javascript client side script in the php server side script
you will need to use ajax call
or
you can use javascript cookie for render javascript variable access in the php
set javascript cookie & get cookie value in the php code using $_COOKIE
javascript cookie value set like :
http://www.w3schools.com/js/js_cookies.asp