关于php:HTML表单选择的jQuery / ajax问题

Html form selected issue with jQuery/ajax

我有一个html表单,其中下拉列表中的国家/地区来自数据库。如果用户选择任何国家,则将根据所选国家/地区显示城市下拉列表。

如果用户错误输入表单的任何字段(此表单中还有其他字段),则国家/地区下拉列表将记住用户最初选择的国家/地区,但清除城市,将其重置为--Select City--。我正在尝试选择城市名称,但不能。有什么主意吗?

此处的HTML格式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<tr>
    <td>PAYS <span style="color: #FF0000;">*</span></td>
    <td>
<select name="country" class="country">
<option value="">Select</option>

<?php
    $sql=mysql_query("select * from country");
    while($row=mysql_fetch_array($sql))
    {
        $id=$row['Code'];
        $data=$row['Name'];
        $data = mb_convert_encoding($data, 'UTF-8');
    if($id == $_POST['country'])
    {
        $sel = 'selected="selected"';
    }
    else
    {
        $sel ="";
    }

        echo '<option value="'.$id.'"' . $sel . '>'.$data.'</option>';
    }
?>
</select>  
</td>
</tr>  

<tr>
<td>City</td>
    <td>
    <select class="city" name="city">
<option selected="selected" value="">--Select City--</option>
</select>  
    </td>
</tr>

此处的Ajax代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"
>
<script type="text/javascript">
$(document).ready(function(){
    $(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;

$.ajax({
    type:"POST",
    url:"ajax_city.php",
    data: dataString,
    cache: false,
    success: function(html)
{
$(".city").html(html);
}
});

});
});

ajax_city.php在这里

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
require_once("toplevel/content/database/databd.php");
if($_POST['id'])
{
    $id=$_POST['id'];
    $sql=mysql_query("select Name from cities WHERE CountryCode ='$id'");
    while($row=mysql_fetch_array($sql))
    {
        $id=$row['Code'];
        $data=$row['Name'];
    if($_POST['city'] == $data)
    {
    $sel = 'selected ="selected"';
    }
    else
    {
    $sel ="";
    }
     echo '<option value="'.$data.'" ' .$sel . ' >'.$data.'</option>';
    }
}
?>


因为在您的AJAX请求中,您将数据定义为POST,并且提供了GET数据样式,该样式需要使用JSON映射。在这种情况下,您的PHP脚本将永远不会收到预期的ID,并且什么也不会发生。

尝试这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$(document).ready(function () {
    $(".country").change(function () {
        var myId = $(this).val();

        $.ajax({
            type:"POST",
            url:"ajax_city.php",
            data:{id : myId},
            cache: false,
            success: function (html) {
                $(".city").html(html);
            },
            error : function(jqXHR, textStatus, errorThrown) {
                alert('An error occurred!')
            }
        });

    });
});


正如我在评论中提到的,快速解决方案是验证客户端,以防止表单无效。这样,您将不会丢失从服务器检索到的城市名称。这不是万无一失的,但是在大多数情况下,它可能会比您现在得到的更温和。

您还可以在页面加载时检查国家/地区选择。如果选择了第一个选项,则您什么也不做,否则调用已用于填充城市下拉列表的ajax。将其放在单独的函数中,以避免代码重复。

1
2
3
4
5
$(document).ready(function() {
    // call ajax if country is selected
    if (document.getElementById('countries').selectedIndex != 0) {
        // call you ajax to populate cities
    }

这假定您将id="countries"添加到国家/地区选择下拉列表中。

我强烈建议您在下拉菜单中添加ID。如果您碰巧也将类名添加到其他元素,则中继唯一的类名并调用$('.city').html()可能会意外地给您带来一些有趣的结果。


确保发布的ID有效。如果id正确,则可以在Mozilla上使用firebug进行查看-

在成功函数中使用append()函数代替html()-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$(document).ready(function () {
    $(".country").change(function () {
        var myId = $(this).val();

        $.ajax({
            type:"POST",
            url:"ajax_city.php",
            data:{id : myId},
            cache: false,
            success: function (html) {
                $(".city").append(html);
            }
        });

    });
});