如何使用Javascript和Ajax将HTML单选按钮值传递给PHP变量?

时间:2013-02-05 23:18:31

标签: php javascript ajax radio

我正在尝试使用Jquery / Javascript和Ajax将用户检查的HTML单选按钮值传递给PHP变量。

以下是HTML / Javascript的简化版本(没有错误检查等)

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
</head>
<body>

<input type="radio"  name="bus_plan" id="smallBtn" value="1"/>
<input type="radio"  name="bus_plan" id="smallBtn" value="2"/>

<script type="text/javascript">
$(document).ready(function()
{
    $("input[name=bus_plan]").on('change', function(){
    var $postID = $('input:radio[name=bus_plan]:checked').val();
    $postID = "="+$postID;
    });
    $.ajax ({
       type: "GET",
       url: "localhost/ajax/product-group.php",
       data: {"postID" : $postID }
    });
});
</script>
</body>
</html>

以下是PHP程序的简化版本(localhost / ajax / product-group.php):

<?php
  $postid = $_GET['postID']; 
  echo "The PostID is ".$postid;
?>

这是在MAMP堆栈上运行。

Javascript工作直到$ .ajax调用,然后PHP程序(localhost / ajax / product-group.php)永远不会被“调用”。

非常感谢任何建议或帮助。

谢谢。

2 个答案:

答案 0 :(得分:0)

替换:

$("input[name=bus_plan]").on('change', function(){
   var $postID = $('input:radio[name=bus_plan]:checked').val();
   $postID = "="+$postID;
});

$.ajax ({
   type: "GET",
   url: "localhost/ajax/product-group.php",
   data: {"postID" : $postID }
});

使用:

$("input[name=bus_plan]").on('change', function(){
    var $postID = $('input:radio[name=bus_plan]:checked').val();
    $postID = "="+$postID;
    $.ajax ({
       type: "GET",
       url: "localhost/ajax/product-group.php",
       data: {"postID" : $postID }
    });
});

或使用您的代码通过在选项中添加 async = false 来生成ajax 异步

使用您的代码,您不知道ajax在单选按钮更改之前或之后的异步之后被调用,将 async = false 添加为ajax选项,您将确保它会同步执行

答案 1 :(得分:0)

在正确缩进代码之前,您无法真正看到问题:

$("input[name=bus_plan]").on('change', function() {
    var $postID = $('input:radio[name=bus_plan]:checked').val();
    $postID = "="+$postID;
});
$.ajax ({
   type: "GET",
   url: "localhost/ajax/product-group.php",
   data: {"postID" : $postID }
});

几个问题:

  1. 您的$postID是更改处理程序的本地
  2. $.ajax()立即运行。
  3. 网址缺少http://个方案。
  4. 您也应该将$.ajax()调用内部移动,以便只有在发生变化时才会运行:

    $("input[name=bus_plan]").on('change', function() {
        var $postID = "=" + $('input:radio[name=bus_plan]:checked').val();
        $.ajax ({
           type: "GET",
           url: "http://localhost/ajax/product-group.php",
           data: {"postID" : $postID }
        });
    });