douhao123457 2018-10-18 18:56
浏览 72
已采纳

尝试通过jQuery.post()将变量从输入无线电传递给PHP

I'm trying to load a html table created by a php code. The table should be generated by an sql query that depends on a variable from a radio input selector, but somehow i can't pass that variable via jQuery.post(). I made a simple version that has the same issue so I hope someone can help me with that:

test.php:

<html>
<head>
    <script type="text/javascript"  src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<script type="text/javascript">
    $(document).ready(function(){

        $("input[name$='selectOP']").on("change", function() {
            var op = $(this).val();
            $.post('ajax.php', {varphp: op});   
            $("#div1").load('ajax.php', function(){             
            });
        });

    });
</script>
<body>
    <label class="radio-inline"><input type="radio" value="110" name="selectOP" id="selectOP">110  </label>
    <label class="radio-inline"><input type="radio" value="115" name="selectOP" id="selectOP">115  </label>
    <div id="div1">
    </div>
</body>
</html>

ajax.php:

<?php
    $var= "Something";
    echo $var;
    //$varphp = $_POST['varphp'];
    //echo $varphp;
?>

So, with the two last lines of ajax.php commented, code successfully runs and the var $var loads inside div1. But if i uncomment those lines, apparently the code stops, and nothing is loaded on div1. What am I doing wrong?

  • 写回答

3条回答 默认 最新

  • dqly83915 2018-10-18 19:05
    关注

    You are calling $.post where you pass the argument and then calling load with no arguments. Of course you can't get $_POST['varphp'] when you call 'load' because you are not passing this variable.

    you must use one of them. you can do with this:

    $.post('ajax.php', {varphp: op}, function(data){ $("#div1").html(data); }, 'html' ); 
    

    or

    $("#div1").load('ajax.php', {varphp: op});
    

    but not both

    thus, your code can be

    $(document).ready(function(){

        $("input[name$='selectOP']").on("change", function() {
            var op = $(this).val();
            $.post('ajax.php', {varphp: op}, function(data){ $("#div1").html(data); }, 'html' ); 
        });
    
    });
    

    or

    $(document).ready(function(){

        $("input[name$='selectOP']").on("change", function() {
            var op = $(this).val();
            $("#div1").load('ajax.php', {varphp: op}); 
        });
    
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向