Home  >  Article  >  Backend Development  >  Examples of methods for JS to call PHP and PHP to call JS

Examples of methods for JS to call PHP and PHP to call JS

ringa_lee
ringa_leeOriginal
2018-05-26 10:25:0546031browse

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="http://www.php.cn/a.js"></script>
<script type="text/javascript" >
    alert(jstext);
</script>

test.php file:

<?php
$php_test=&#39;I like PHP中文网!&#39;;
echo "var test=&#39;$php_test&#39;;";
echo "var jstext="."&#39;$php_test&#39;;"; 
?>

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=&#39;text/javascript&#39;>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 = &#39;CALL_ME_WHY&#39;;    //定义变量
?>
<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(&#39;Y&#39;)?>,M=<?php echo date(&#39;n&#39;)?>,D=<?php echo date(&#39;j&#39;)?>;
	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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn