如何在同一页面中将jQuery变量发布到PHP? [英] How to POST jQuery variables to PHP in same page?

查看:52
本文介绍了如何在同一页面中将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("http://freegeoip.net/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("http://freegeoip.net/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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆