我正试图使用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)永远不会被"调用"。
任何建议或帮助都将不胜感激。
谢谢。
替换:
$("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选项,您将确保它将同步执行
只有正确缩进代码才能真正看到问题:
$("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 }
});
少数问题:
- 您的
$postID
是变更处理程序的本地 $.ajax()
立即运行- URL缺少
http://
方案
您也应该将$.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 }
});
});