Home > Article > Backend Development > Examples of methods for JS to call PHP and PHP to call JS
JS calls PHP and PHP calls JS. The editor makes the following summary, hoping to help everyone;
First of all: JS method Call the PHP file and get the value in PHP; the following example illustrates:
For example, in the page test_1, is called with the following sentence:
<!--举例引用示例,这个js文件不存在,该js文件改成你自己的--> <script type="text/javascript" src="//m.sbmmt.com/a.js"></script> <script type="text/javascript" > alert(jstext); </script>
test.php file:
<?php $php_test='I like PHP中文网!'; echo "var test='$php_test';"; echo "var jstext="."'$php_test';"; ?>
When executing the test.php file, The test_1.php file will be called, and the output of the b.php file will be executed as a JS statement,
so here it will A prompt box pops up, the content is the value of the JS variable jstext, which is the value assigned to jstext in the PHP file.
Summary: Use JS to call files in HTML to call PHP file, the output of the PHP file will be used as JS code by the calling page.
PHPcalls the value in JS
There is such a piece of code in the test.php page:
<script type="text/javascript" > var data="call_me_why"; </script> <? echo "<script type=text/javascript>document.write(data)</script>"; ?>
php calls the method (function) in js
It is basically the same as the second case Similarly, use echo scripts to implement JS calls
<script type="text/javascript"> function test() { var t1=3; t1 = t1+2; alert(t1); //return t1; } </script> <?php echo "<script type='text/javascript'>test();</script>"; ?>
JS calls PHP variables (1)
<?php $userId=100; ?> <script> var userId; userId=document.getElementById("userId").value; alert(userId); </script> <input type="text" name="userId" id="userId" value="<?php echo $userId; ?>">
(2)
<?php $url = 'CALL_ME_WHY'; //定义变量 ?> <script type="text/javascript"> //js调用php变量 var ds ="<?php echo $url?>" ; //赋值 alert(ds); //输出效果 </script>
JS calls PHP function
<script language="JavaScript"> var Y=<?php echo date('Y')?>,M=<?php echo date('n')?>,D=<?php echo date('j')?>; alert(Y); alert(M); alert(D); </script>
The above is the detailed content of Examples of methods for JS to call PHP and PHP to call JS. For more information, please follow other related articles on the PHP Chinese website!