Home Backend Development PHP Tutorial Summary of methods for calling php from js and calling js from php

Summary of methods for calling php from js and calling js from php

Jul 14, 2018 am 11:27 AM

This article mainly introduces a summary of the methods of JS calling PHP and PHP calling JS. It has certain reference value. Now I share it with you. Friends in need can refer to it.

1 JS method of calling PHP file and get the value in php

Give a simple example to illustrate:

For example, in page a.html, use the following sentence to call:

<script type="text/javascript" src="b.php?action=test"></script>
<script type="text/javascript" >
alert(jstext);
</script>
Copy after login

In b. There is such a piece of PHP code in php:

<? $action=$_GET[&#39;action&#39;]; //echo "var jstext=&#39;$action&#39;"; //输出一句JS语句,生成一个JS变量,并赋颠值为PHP变量 $action的值 //echo "var jstext=&#39;aa&#39;"; echo "var jstext="."&#39;$action&#39;"; ?>
Copy after login

When the a.html file is executed, the b.php file will be called, and the output of the b.php file will be executed as a JS statement, so a pop-up will appear here A prompt box whose 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 the file in HTML to call the PHP file , then the output of the PHP file will be used as JS code by the calling page.

2 PHP calls the value in js

There is such a piece of code in the z.php page:

<script type="text/javascript" > var url="aaaa*"; </script> <? $key="<script type=text/javascript>document.write(url)</script>"; echo $key; ?>
Copy after login

3 php calls methods (functions) in js

<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>"; ?>
Copy after login

4 JS calls PHP variables

(1)

<?php
$userId=100;
?> <script>
var userId;
userId=document.getElementByIdx_x_x_x("userId").value;
alert (userId);
</script>
<input type="text" name="userId" id="userId" value="<?php echo $userId; ?>">
Copy after login

(2)

<?php$url = &#39;变化的网址&#39;;    //定义变量?><script type="text/javascript">//js调用php变量var ds ="<?php echo $url?>" ; //赋值 alert(ds); //输出效果 </script>
5  -------------------------------
<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;)?>;
-->
</script>
Copy after login

6 The js and php written by myself call each other

1.php content:

<?php
 
//echo "<script LANGUAGE=&#39;javascript&#39;>alert(&#39;$php变量&#39;);</script>";   //最简单的php调用js
//echo "<a href=#><img width=50 src=&#39;$fruit_pic_array[$i]&#39; onMouseOver=’javascript:a();‘></a>";
//echo "<a href=&#39;3.php&#39;>aaaa</a>";   //php中超链接
 
//echo "<script type=&#39;text/javascript&#39; language=&#39;javascript&#39;>phpmake(&#39;PHP建站学习笔记网&#39;);</script>";   //有时候需要在PHP执行过程中,需要调用JavaScript自定义函数(验证时出错)
echo "function ok(msg){alert(msg);}";
?>
Copy after login
<HTML>
<HEAD>
<TITLE> php调用js文件的好办法</TITLE>
</HEAD>
<BODY>
<!--js调用php中定义的js-->
<scrīpt language=&#39;&#39;javascrīpt&#39;&#39; type=&#39;&#39;text/javascrīpt&#39;&#39; src=&#39;&#39;1.php&#39;&#39;></scrīpt>  
<scrīpt>
ok("aaaaaa!");
</scrīpt>
</script>
</BODY>
</HTML>
Copy after login

2.php content:

<!--js调用php-->

<?php
$userId=100;
?>

<script>
var userId;
userId=document.getElementByIdx_x("userId").value;
alert (userId);
</script>
<input type="text" name="userId" id="userId" value="<?php echo $userId; ?>">

 

 

<!--js调用php-->

<?php

if($_GET["action"]=="ok")

{

echo "I&#39;m OK!";

}

else

{

echo "I&#39;m not OK!";

}

?>

<SCRIPT Language = "JavaScript">

function func()

{

if(confirm("Are you OK with this?"))

{

this.location = "ok.php?action=ok";

}

else

{

this.location = "ok.php?action=cancel";

}

}

</SCRIPT>

<html>

<head>

</head>

<body>

<a href="#" href="#" onClick="javascript:func();">Please Click</a>

</body>

</html>
Copy after login

<html>
<head>
    <script>
        function isMail(PostString) {
            re = /\w*/
            if (re.test(PostString)) {
                return true;
            } else {
                return false;
            }
        }

        function test() {
            if (isMail(<?php echo $email?>)) {
                document.write("<?php echo "N";?>");
            } else {
                document.write(&#39;<?php echo &#39;Y&#39;;?>&#39;);
            }
        }
    </script>
</head>
<body>
<?php
$email = "aa";
?>

<input type=button value=click onclick=&#39;test() &#39;>
</body>
</html>


<!--php中含有js代码-->

<?php
echo "<script   language=javascript>
  function test(){
    alert( &#39;hello &#39;);    
  }
</script> ";
?>
<input type=button value=click onclick=&#39;test() &#39;>
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

PHP generates QR code for WeChat applet with parameters

For the five principles of PHP object-oriented design ( SOLID) Summary

The above is the detailed content of Summary of methods for calling php from js and calling js from php. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles