js变量怎么传递给php变量

PHPz
Release: 2020-09-05 10:20:57
Original
3581 people have browsed it

js变量传递给php变量的方法:首先执行else部分;然后输出js脚本到浏览器上;接着在浏览器中运行js;最后提交表单并跳转到相关页面即可。

js变量怎么传递给php变量

js变量怎么传递给php变量?

首先要知道php语言是经过后端服务器解析执行的,  而js语言的执行环境是需要在浏览器上运行.在后端php是没有办法执行的,只能返回给前端的浏览器去执行.  如果js变量想传递给php使用,那么有个办法就是利用ajax通讯从前端浏览器上传递给后端php执行. php和js同一个页面具体例子如下(demo.php文件):   

实际过程是先执行else部分然后输出js脚本到浏览器上 --> 浏览器运行js, 3s后提交表单并跳转到本页面->  后台接收到请求执行了if部分, 最后输出结果

<?php  
 
if (isset($_REQUEST[&#39;submit&#39;])) {
    echo var_export($_REQUEST, true); //echo出所有接收到的参数
} else {
    echo <<<SCRIPT
//jq.js是jq文件,可以自己引入本地正确的jq文件路径或者引用线上的jq路径也可
<script src="./jq.js"></script>
<form action="">
    <input type="text" name="param" value="helo">
    <input type="text" name="data" value="world">
    <input type="submit"/>
</form>
<script>
   
    setTimeout(function() {
          $("[type = &#39;submit&#39;]").click();
    }, 3000);
    
    function ajax() {
        $.ajax({
            &#39;url&#39;: &#39;./demo.php&#39;,
            &#39;method&#39;: &#39;post&#39;,
            &#39;data&#39;: {a: 10, b: 20, data: 1231},
            success: function (result) {
                console.log(result);
            },
            error: function (result) {
                console.log(result);
            }
        })
    }
</script>
SCRIPT;
 
}
?>
Copy after login

 

更多相关知识,请访问PHP中文网

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!