[英]Can't display radio button value using AJAX and PHP
我在显示当前正在使用的基本Web应用程序中单击单选按钮的值时遇到问题。
这是我的ajax.js文件:
$('#selection').change(function() {
var selected_value = $("input[name='kobegreat']:checked").val();
$.ajax( {
url: "kobegreat.php",
data: selected_value,
type: "POST",
datatype: "json",
success: function(json) {
var test1 = $("<p></p>").text(json["name"]);
$("h3").append(test1);
alert("AJAX was a success");
},
cache: false
});
});
和我的kobegreat.php文件:
<?php
if($_SERVER['REQUEST_METHOD] == "POST") {
$value = $POST['kobegreat'];
$return = $_POST;
if($return["name"] == "") {
$return["name"] = $value;
}
echo json_encode($return);
}
?>
HTML代码,我试图在以下方面显示我的价值:
<h2>Select a Great Kobe Moment.</h2>
<form id="selection" method="get">
<input type="radio" name="kobegreat" value="kobe1" checked/>Kobe1
<input type="radio" name="kobegreat" value="kobe2"/>Kobe2
<input type="radio" name="kobegreat" value="kobe3"/>Kobe3
</form>
<div id="target">
<h3>Great Kobe Moment!</h3>
</div>
我想要的只是让程序在网页上显示的标题之一下显示值,但不会这样做。 我收到AJAX在completed:部分中运行的警报,但是在日志中还显示一条错误,提示未定义json。 到处寻找有关此问题的帮助,提前感谢您的帮助。
如果我正确理解您的意思,那么您只需尝试将所选单选按钮的名称传递给kobegreat.php文件,然后将其返回作为响应。 尝试这个:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<body>
<h2>Select a Great Kobe Moment.</h2>
<form id="selection" method="get">
<input type="radio" name="kobegreat" value="kobe1" checked/>Kobe1
<input type="radio" name="kobegreat" value="kobe2"/>Kobe2
<input type="radio" name="kobegreat" value="kobe3"/>Kobe3
</form>
<div id="target">
<h3>Great Kobe Moment!</h3>
</div>
<script>
$('#selection').change
(
function()
{
var selected_value = $("input[name='kobegreat']:checked").val();
$.ajax
(
{
url: "kobegreat.php",
dataType : "json",
method: "POST",
cache: false,
data: { selected_value : selected_value },
success: function(response)
{
var test1 = "<p>"+response+"</p>";
$("h3").append(test1);
alert("AJAX was a success");
}
}
);
}
);
</script>
</body>
</html>
kobegreat.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$value = filter_input(INPUT_POST, "selected_value");
if (isset($value))
{
echo json_encode($value);
}
}
建议 :永远不要直接访问超全局$ _POST数组,请始终使用过滤器功能,因为它更安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.