如何使用ajax和php从select选项中获取值

时间:2016-04-29 07:43:06

标签: php jquery ajax

我有2个选择框选项,城市和地区。当我在城市选择时,我使用ajax去获取地区名称。对于这个过程我已经成功但是当我点击提交时,我收到错误消息Undefined index:district,你可以看到这张图片 result image

这是我的ajax代码:

 $(document).ready(function($) {
    $("#city").change(function() {
        var search_id = $(this).val();
        $.ajax({
            url: "search.php",
            method: "post",
            data: {search_id:search_id},
            success: function(data){
                $("#district").html(data);
            }
        })
    });
});

这是HTML代码:

   

 <form action="" method="post">
    select city:
    <select name="city" id="city">
    	<option value="1">Phnom Penh</option>
    	<option value="2">Kampong Soam</option>
      <option value="3">Siem Reap</option>
    </select>

    select district:
    <select name="distrcit" name="district" id="district">
    	<option>Select District</option>
    </select>

    <input type="submit" name="submit">
    </form>

这是PHP代码:

<?php 
if(isset($_POST['submit'])){
	echo $_POST['city'];
	echo $_POST['district'];
}

 ?>

//ajax request
<?php 
if(isset($_POST['search_id'])){
	$search_id = $database->escape_string($_POST['search_id']);

	if(!empty($search_id)){
		// $output = array();
		$sql = "SELECT * FROM district WHERE ref_id = '$search_id'";
		$districts = District::find_this_query($sql);
		foreach($districts as $district){
			// echo $district->id;
			// echo $district->district_name;
			$output .= "<option value='{$district->id}'>{$district->district_name}</option>";
		}

		echo $output;
	}
	
 }
?>

5 个答案:

答案 0 :(得分:1)

您在选择框中设置了两次名称。仅指定一次名称:

所以吧:

<select name="district" id="district">
    <option>Select District</option>
</select>

答案 1 :(得分:1)

在HTML中,您已声明了2次名称属性:

<select name="distrcit" name="district" id="district">

请替换为:

<select name="district" id="district">

答案 2 :(得分:1)

我认为这种方式不是很干净,您可以创建一个以json格式返回值的ajax请求,然后使用

将结果添加到select标记中
new Option(text, value);

答案 3 :(得分:1)

请仅限一次名称:

<select name="district" id="district">
<option>Select District</option>

答案 4 :(得分:0)

   

 <form action="" method="post">
    select city:
    <select name="city" id="city">
    	<option value="1">Phnom Penh</option>
    	<option value="2">Kampong Soam</option>
      <option value="3">Siem Reap</option>
    </select>

    select district:
    <select name="distrcit" name="district" id="district">
    	<option>Select District</option>
    </select>

    <input type="submit" name="submit">
    </form>