js变量传递给php变量的方法:首先执行else部分;然后输出js脚本到浏览器上;接着在浏览器中运行js;最后提交表单并跳转到相关页面即可。
js变量怎么传递给php变量?
首先要知道php语言是经过后端服务器解析执行的, 而js语言的执行环境是需要在浏览器上运行.在后端php是没有办法执行的,只能返回给前端的浏览器去执行. 如果js变量想传递给php使用,那么有个办法就是利用ajax通讯从前端浏览器上传递给后端php执行. php和js同一个页面具体例子如下(demo.php文件):
实际过程是先执行else部分然后输出js脚本到浏览器上 --> 浏览器运行js, 3s后提交表单并跳转到本页面-> 后台接收到请求执行了if部分, 最后输出结果
<?php if (isset($_REQUEST['submit'])) { 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 = 'submit']").click(); }, 3000); function ajax() { $.ajax({ 'url': './demo.php', 'method': 'post', 'data': {a: 10, b: 20, data: 1231}, success: function (result) { console.log(result); }, error: function (result) { console.log(result); } }) } </script> SCRIPT; } ?>
更多相关知识,请访问PHP中文网!