问题描述
<html>
<?php
$num = 1;
echo $num;
?>
<input type="button"
name="lol"
value="Click to increment"
onclick="Inc()" />
<br>
<script>
function Inc()
{
<?php
$num = 2;
echo $num;
?>
}
</script>
</html>
这是我迄今为止,没有工作,虽然,我想我需要使用Ajax或东西,但我不知道该怎么做。
This is what i have so far, not working though, i think i need to use ajax or something but i have no idea what to do.
感谢
推荐答案
您不能运行PHP code的JavaScript。当用户临危页面,则服务器将评估和运行所有的PHP code和取出来。因此,例如,这将工作:
You can't run PHP code with Javascript. When the user recieves the page, the server will have evaluated and run all PHP code, and taken it out. So for example, this will work:
alert( <?php echo "\"Hello\""; ?> );
由于服务器已经评估到这一点:
Because server will have evaluated it to this:
alert("Hello");
但是,你不能使用它进行PHP中的任何操作。
However, you can't perform any operations in PHP with it.
本:
function Inc()
{
<?php
$num = 2;
echo $num;
?>
}
将只进行了评估,以这样的:
Will simply have been evaluated to this:
function Inc()
{
2
}
如果您wan't调用PHP脚本,你必须调用不同的网页,其中从一组参数返回一个值。
If you wan't to call a PHP script, you'll have to call a different page which returns a value from a set of parameters.
这,例如,将工作:
运行script.php
script.php
$num = $_POST["num"];
echo $num * 2;
的Javascript(jQuery的)(在另一页):
Javascript(jQuery) (on another page):
$.post('script.php', { num: 5 }, function(result) {
alert(result);
});
这应警惕10。
祝你好运!
编辑:刚才递增数的页面上可以jQuery中很容易地完成这样的: http://jsfiddle.net/puVPc/一>
Just incrementing a number on the page can be done easily in jQuery like this: http://jsfiddle.net/puVPc/
这篇关于在JavaScript函数如何使用PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!