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条)

报告相同问题?

悬赏问题

  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题