dongyi8795 2011-01-20 20:20
浏览 23
已采纳

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

I was looking around for a ajax script which could populate triple drop down list using PHP. And I came across this piece of code although the code works pretty well I would like to know what is actually happening behind the scene, as I am a newbie to AJAX or JavaScript I am unable to understand what does the below function exactly do. Here is the code:

<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:
" + 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:
" + req.statusText);
                    }
                }               
            }           
            req.open("GET", strURL, true);
            req.send(null);
        }

    }
</script>

and here is the code from 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>

and this is 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>

My questions :

a) Can anyone please summarize the first, second and third javascript function and how does it select all the values from findState.php and findCity.php

b) If I was to catch the value of the stateId and CityId the user selected how do i do it. as because the list is populated from JavaScript I am unable to catch the value from PHP ($_POST['state']).

  • 写回答

1条回答 默认 最新

  • douwei7203 2011-01-20 20:42
    关注

    The first function is attempting to open up and XML HTTP request, allowing the clients-side scripts to interact with server-size scripts. Since various browsers handle that differently, it trys to use the standard method before attempting a modern IE implementation, an older IE implementation and finally giving up.

    The second two do roughly the same thing. They define the script they wish to interact with an use the first function to connect. If the connection was successful, it sends over the information using an HTTP GET request (traditionally GET is used for getting information, POST is used for setting it). When information is sent using XmlHttpRequest, the onreadystatechange event fires at key points during the connection and gives access to the readyState (referring to how the stage of the request) and the status which is a standard server response (you're probably familiar with "404" meaning "file not found"). A "200" status means "everything is fine", so when that is received the script knows it can act on the information it was given. Any other response will create a popup that tells the user what went wrong.

    Without seeing the actual page this script interacts with, I don't know the best way to get stateId and CityId. At a guess, they will be the value of an input when a certain button is pressed. If that's the case, something like the following piece of code would do it:

    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;
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料