无法使用$ _POST检索所选下拉选项中的值

时间:2017-04-07 15:44:49

标签: php ajax

我似乎无法将select.php中的选定选项值输入value_selected.php文件。console.log(data)什么都没显示。那是为什么?

select.php

<!DOCTYPE html>  
<html>  
<head></head>
<body>
<script src="js/jquery-3.2.0.min.js"></script>

<form method="POST" action="">
<label for "sel_opt">Select value: </label>
<select name="sel_opt" id="sel_opt">
    <option value="1">1</option>
    <option value="2">2</option>
</select>
<input name="submit" type="submit" id="submit" value="Submit">
</form>

<div id="result"></div>

<script>
$(document).ready(function(){  
           $("#submit").click(function(){ 
             $.ajax({  
                          url:"http://localhost/value_selected.php",  
                          type:"POST",  
                          success:function(data)  
                          {  
                            console.log(data);
                            $('#result').html(data);  
                          }  
                     });  
                });  
           }); 
</script>
</body>
</html>

value_selected.php

<?php
$output = "";
if(isset($_POST["submit"])) {
 if(isset($_POST["sel_opt"])) {
$val = $_POST["sel_opt"];
 if ($val == 1) {  
      $output = "<p>Value 1 selected</p>";
 }   else {
    $output = "<p>Value 2 selected</p>";
 }
 echo $output;
}
 ?>

1 个答案:

答案 0 :(得分:1)

使用表单值将data:添加到a​​jax配置对象。

<script>
$(document).ready(function(){
    $("#submit").click(function(){
        $.ajax({
            url:"http://localhost/value_selected.php",
            type:"POST",
            data: $('form').serialize(),
            success:function(data)
            {
                console.log(data);
                $('#result').html(data);
            }
        });
    });
});
</script>