这个javascript函数究竟做了什么?以及如何从select中捕获值以将其插回到数据库中?

时间:2011-01-20 20:20:04

标签: php javascript ajax

我正在寻找一个可以使用PHP填充三重下拉列表的ajax脚本。我遇到了这段代码,虽然代码工作得很好我想知道幕后实际发生了什么,因为我是AJAX或JavaScript的新手,我无法理解下面的函数究竟做了什么。这是代码:

<script language="javascript" type="text/javascript">

function getXMLHTTP() { //function to return the xml http object
        var xmlhttp=false;  
        try{
            xmlhttp=new XMLHttpRequest();
        }
        catch(e)    {       
            try{            
                xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){
                try{
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch(e1){
                    xmlhttp=false;
                }
            }
        }

        return xmlhttp;
    }

    function getState(countryId) {      

        var strURL="findState.php?country="+countryId;
        var req = getXMLHTTP();

        if (req) {

            req.onreadystatechange = function() {
                if (req.readyState == 4) {
                    // only if "OK"
                    if (req.status == 200) {                        
                        document.getElementById('statediv').innerHTML=req.responseText;                     
                    } else {
                        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                    }
                }               
            }           
            req.open("GET", strURL, true);
            req.send(null);
        }       
    }
    function getCity(stateId) {     
        var strURL="findCity.php?state="+stateId;
        var req = getXMLHTTP();

        if (req) {

            req.onreadystatechange = function() {
                if (req.readyState == 4) {
                    // only if "OK"
                    if (req.status == 200) {                        
                        document.getElementById('citydiv').innerHTML=req.responseText;                      
                    } else {
                        alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                    }
                }               
            }           
            req.open("GET", strURL, true);
            req.send(null);
        }

    }
</script>

这是来自finsState.php的代码

<?php
$countryId=intval($_GET['country']);
$host = "localhost";
$username = "username";
$password = "password";
$database = "test";
$connection = mysql_connect($host,$username,$password) or die(mysql_error());
$database = mysql_select_db($database) or die(mysql_error());
$query = "SELECT * FROM states WHERE country_id = ".$countryId;
$result = mysql_query($query) or die(mysql_error());
?>
<select name="states" onchange="getCity(this.value)">
<option>Select State</option>
<?php while($row = mysql_fetch_array($result)) { ?>
    <option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
<?php } ?>
</select>

这是findCity.php

<?php
$stateId=intval($_GET['state']);
$host = "localhost";
$username = "username";
$password = "password";
$database = "test";
$connection = mysql_connect($host,$username,$password) or die(mysql_error());
$database = mysql_select_db($database) or die(mysql_error());
$query = "SELECT * FROM cities WHERE state_id = ".$stateId;
$result = mysql_query($query) or die(mysql_error());
?>
<select name="city">
<option>Select City</option>
<?php while($row = mysql_fetch_array($result)) { ?>
    <option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?> </option>
<?php } ?>
</select>

我的问题:

a)任何人都可以总结第一,第二和第三个javascript函数,以及它如何从findState.php和findCity.php中选择所有值

b)如果我要捕获stateId和CityId的值,用户选择我该怎么做。因为列表是从JavaScript填充的,所以我无法从PHP中捕获值($ _POST ['state'])。

1 个答案:

答案 0 :(得分:2)

第一个功能是尝试打开XML HTTP请求,允许客户端脚本与服务器大小的脚本进行交互。由于各种浏览器处理方式不同,因此try在尝试现代IE实现之前使用标准方法,较旧的IE实现并最终放弃。

第二个做大致相同的事情。他们定义了他们希望与之交互的脚本,并使用第一个连接函数。如果连接成功,它将使用HTTP GET请求发送信息(传统上,GET用于获取信息,POST用于设置它)。 当使用XmlHttpRequest发送信息时,onreadystatechange事件在连接期间的关键点触发,并允许访问readyState(指代请求的阶段)和status标准服务器响应(您可能熟悉“404”,意思是“找不到文件”)。 “200”状态意味着“一切都很好”,因此当收到该状态时,脚本知道它可以对其给出的信息采取行动。任何其他响应都会创建一个弹出窗口,告诉用户出了什么问题。

如果没有看到此脚本与之交互的实际页面,我不知道获取stateId和CityId的最佳方法。猜测,当按下某个按钮时,它们将是输入的值。如果是这种情况,就像下面的代码一样:

document.getElementById('id-of-submit-button').onclick = function() {
    var stateId = document.getElementById('id-of-stateid-input').value,
        CityId  = document.getElementById('id of cityid-input').value;
};