本文介绍了如何在同一页面中将jQuery变量发布到PHP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
两者我的 jQuery 代码和 PHP 代码在同一PHP文件中(不是两个单独的文件).
Both my jQuery code and PHP code are in the same PHP file (not two separate files).
我想将jQuery变量发布到PHP代码.
I want to POST jQuery Variable to the PHP code.
但是在运行PHP文件时会显示一些错误(未定义的索引").
But it Shows some errors ("undefined index") when running the PHP file.
PHP文件如下(test.php).
PHP file is as follows (test.php).
<?php $country = $_POST['userCountry']; $ip = $_POST['userIp']; echo $country; echo $ip; ?> <html> <head><title></title> <script src = "jquery.min.js"></script> <script> $.getJSON("freegeoip/json/", function(data) { var country = data.country_name; var ip = data.ip; $.ajax({ method:"POST", url:"test.php", data:{userCountry:country, userIp:ip} }); }); </script> </head> <body></body> </html>推荐答案
<?php if(!empty($_POST)){ $country = $_POST['userCountry']; $ip = $_POST['userIp']; echo $country; echo $ip; } ?> <html> <head><title></title> <script src = "jquery.min.js"></script> <script> $(document).ready(function(){ $.getJSON("freegeoip/json/", function(data) { var country = data.country_name; var ip = data.ip; $.ajax({ method:"POST", url:"test.php", data:{userCountry:country, userIp:ip}, success:function(result){ $('body').html(result); } }); }); }); </script> </head> <body></body> </html>
尝试此代码.刚刚测试好了
Try this code. Just Tested OK
更多推荐
如何在同一页面中将jQuery变量发布到PHP?
发布评论