可以't使用AJAX和PHP显示单选按钮值

Can't display radio button value using AJAX and PHP

本文关键字:PHP 显示 单选按钮 AJAX 使用 可以      更新时间:2024-06-30

我在显示当前正在使用的基本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数组,请始终使用筛选器函数,因为它更安全。