Ajax没有连接到数据库?

时间:2016-04-09 12:13:20

标签: javascript php html ajax

我已经制作了一个html文件文件,我希望ajax在后台连接到数据库,以根据用户预先选择的国家/地区获取所选城市的值。简而言之,当用户在第一个下拉菜单中选择国家时,我只需要数据库自动加载所有城市下拉菜单?

<!doctype>
<html>
<head>
<title></title>
</head>

<body>
<form method="GET" action="" name="form1">
Country : <select name="country" onchange="getCity('ind.php?   country='+this.value)">
 <option value="">Select Country</option>
 <option value="1">USA</option>
 <option value="2">Canada</option>
 </select>
<br />City : <div id="citydiv">
 <select name="select">
 <option>Select City</option>
    </select>
</div>
</form>



<script>

function getCity(strURL)
{         
 var req = getXMLHTTP(); // fuction to get xmlhttp object
 if (req)
 {
  req.onreadystatechange = function()
 {
    if (req.readyState == 4) { //data is retrieved from server
    if (req.status == 200) { // which reprents ok status                    
    document.getElementById('citydiv').innerHTML=req.responseText;
  }
 else
  { 
     alert("There was a problem while using XMLHTTP:\n");
  }
  }            
  }        
 req.open("GET", strURL, true); //open url using get method
 req.send(null);
 }
}
</script>

</body>
</html>

ind.php

<?php 
    $country=$_GET['country'];
    $link = mysql_connect('localhost', 'root', ''); /change the configuration if required
    if($link)
    {
       echo "connect";
    }
    if (!$link) {
    die('Could not connect: ' . mysql_error());
    }
    mysql_select_db('country'); //change this if required
    $query="select city from city where countryid=$country";
    $result=mysql_query($query);
 ?>
    <select name="city">
    <option>Select City</option>
    <?php while($row=mysql_fetch_array($result)) ?>
   <option value><?php=$row['city']?></option>

</select>

1 个答案:

答案 0 :(得分:0)

制作AJAX请求不会更改您的网址,除非您在进行AJAX调用后使用javascript一次/在/之后立即进行更改。

  

要使用javascript更改网址,您可以使用类似的内容 -

location.replace("http://new-url");