如何在同一页面中将jQuery变量发布到PHP?

编程入门 行业动态 更新时间:2024-10-10 10:29:25
本文介绍了如何在同一页面中将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?

本文发布于:2023-10-10 18:39:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1479401.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   变量   页面   在同一   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!