在document.ready jquery上运行ajax请求

时间:2015-02-07 04:51:59

标签: javascript php jquery html ajax

Ajax

$(document).ready(function() {
    $.ajax({
        type: 'POST',
        url: '../include/ListOfCities.php',
        dataType: "json",
        data: {
            Country: "Japan"
        },
        success: function(data) {
            console.log(data);
            var city = ('#city');
            $(city).empty();
            for (var i = 0; i < data.length; i++) {
                $(city).append('<option id=' + data[i].sysid + ' value=' + data[i].city_name + '>' + data[i].city_name + '</option>');

            }
        }

    });
});

PHP

$country = mysql_real_escape_string($_POST['Country']);
$stmt = $dbh->prepare("SELECT * FROM city_tbl WHERE country_name = ? ");
$stmt->bindValue(1, $country, PDO::PARAM_STR);
if ($stmt->execute()) {
    if ($stmt->rowCount() > 0) {
        while ($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $citylist[] = array('sysid' => $selected_row['sys_id'], 'code' => $selected_row['city_code'], 'name' => $selected_row['city_name'], 'parentid' => $selected_row['parent_id']);
        }
        $input = array_map("unserialize", array_unique(array_map("serialize", $citylist)));
        echo json_encode($input, JSON_UNESCAPED_UNICODE);
    }
}

我想在选择选项菜单中显示日本的所有城市我希望在页面加载时加载城市我发送上面的ajax请求但我没有得到任何结果上面的ajax工作正常我在按钮上使用它。发送ajax请求不同于按钮单击和文档就绪。任何建议如何在文档准备好的ajax请求是赞赏

1 个答案:

答案 0 :(得分:8)

尝试在您的ajax请求中设置async:false。所以最终的代码将是

$(document).ready(function() {
    $.ajax({
        type: 'POST',
        url: '../include/ListOfCities.php',
        dataType: "json",
        async:false,
        data: {
            Country: "Japan"
        },
        success: function(data) {
            console.log(data);
            var city = ('#city');
            $(city).empty();
            for (var i = 0; i < data.length; i++) {
                $(city).append('<option id=' + data[i].sysid + ' value=' + data[i].city_name + '>' + data[i].city_name + '</option>');

            }
        }

    });
});