XMLHttpRequest在FF中返回但不是IE

时间:2012-01-09 18:10:57

标签: php ajax internet-explorer xmlhttprequest

我正在尝试进行AJAX调用,根据另一个下拉框的选择,将数据拉回到弹出下拉框。我的代码在FF 9.0.1(用于firebug)中工作正常,但在IE 7中失败(这是我的公司标准)。我已经尝试了几种方法来显示数据,我现在没有时间学习如何在jQuery中执行此操作。我确信这将是一个头脑,但是IE导致这个问题呢?

以下是我的代码页。首先是调用JavaScript的表单的修剪版本。

<html>
<head>
<script language="JavaScript" src="/includes/Transaction_Update.js"></script>
<form id="submit" name="submit" action="Transaction_Process.php" method="post">
    <table align='left'>
      <tr>
        <td class='reporttd'>Vendor</td>
        <td>
          <select name='selVendorCode' id='selVendorCode' onChange="getServiceCode()">
            <option value='' selected='selected'></option>
            <?php echo $vendorOptionList; ?>
          </select>
        </td>
      </tr>
      <tr>
        <td class='reporttd'>Service Code</td>
        <td class='reporttd'>
          <select name='selServiceCode' id='selServiceCode'>
            <option value='' selected='selected'></option>
          </select>
        </td>
      </tr>
    </table>  
  </div>
</div>
</form>

JavaScript页面

//setup xmlHttp request for Ajax call
var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject(){

    var xmlhttp;
    try{
        xmlHttp = new XMLHttpRequest();
    }
    catch(e)
    {
        var xmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                        "MSXML2.XMLHTTP.5.0",
                                        "MSXML2.XMLHTTP.4.0",
                                        "MSXML2.XMLHTTP.3.0",
                                        "MSXML2.XMLHTTP",
                                        "Microsoft.XMLHTTP");
        for (var i=0; i<xmlHttpVersions.length && !xmlHttp; i++){
            try{
                xmlHttp = new Activexobject(xmlHttpVersions[i]);
            }
            catch(e) {}
        }
    }

    if (!xmlHttp){
        alert("Error creating the XMLHttpRequest object.");
    }
    else{
        return xmlHttp;
    }
}
//Call page to get all service codes for a vendor.
function getServiceCode(){  
    if (xmlHttp){
        try{
            var vCode = document.getElementById("selVendorCode").value;
            var parms = "vCode=" + vCode;

            //Call Transaction_AJAX.php to pass back an XML.
            xmlHttp.open("GET", "Transaction_AJAX.php?" + parms, true);
            xmlHttp.onreadystatechange = handleRequestStateChange;
            xmlHttp.send(null);
        }
        catch(e){
            alert("Can't connect to server:\n" + e.toString());
        }
    }
}

//Checks state of the HTTP request call, and proceed if status is ready
function handleRequestStateChange(){
    if (xmlHttp.readyState == 4){
        if(xmlHttp.status == 200){
            try{
                handleServerResponse();
            }
            catch(e){
                alert("Error reading the response: " + e.toString());
            }
        }
        else{
            alert("There was a problem retrieving the data:\n" + xmlHttp.StatusText);
        }
    }
}

//Handles response from the server
function handleServerResponse(){
    var xmlResponse = xmlHttp.responseXML;
        if (!xmlResponse || !xmlResponse.documentElement){
        throw("Invalid XML Structure:\n" + xmlHttp.responseText);
    }

    var rootNodeName = xmlResponse.documentElement.nodeName;
    if(rootNodeName == "parsererror"){
        throw("Invalid XML Structure:\n" + xmlHttp.responseText);
    }

    xmlRoot = xmlResponse.documentElement;
    if(rootNodeName != "root" || !xmlRoot.firstChild){
        throw("Invalid XML structure:\n" + xmlHttp.responseText);
    }

    //Get response and load it into drop down
    responseText = xmlRoot;

    var sel = document.getElementById("selServiceCode");
    sel.options.length = 0;
    var opt = document.createElement("option");
    document.getElementById("selServiceCode").options.add(opt);
    for(var i=0; i < responseText.childElementCount; i++){
        var newOpt = new Option(responseText.childNodes[i].childNodes[1].textContent,responseText.childNodes[i].childNodes[0].textContent);
        sel.options[sel.options.length] = newOpt;
    }
}

创建XML文件的PHP页面

<?php
header('content-type:text/xml; charset=utf-8');

include("../includes/DBConn.php");

$vCode = $_GET['vCode'];

///Setup cursers and proc command
$curs = OCI_New_Cursor($c); 
$stmt = OCI_Parse($c,"begin schema.package.procedure(:var_code, :expected_cv); end;");

OCI_Bind_By_Name($stmt, ":var_code", $vCode);
OCI_Bind_By_Name($stmt,":expected_cv",&$curs,-1,OCI_B_CURSOR);

//execute statment and cursors
oci_execute($stmt); 
oci_execute($curs); 

//Create xml document
$dom = new DOMDocument('1.0', 'UTF-8');

$root = $dom->createElement('root');
$root = $dom->appendChild($root);

//loop through results of Proc
while (ocifetchinto($curs,&$vendor_cv )) { 

    //Add node for each row
    $occ = $dom->createElement("cell");
    $occ = $root->appendChild($occ);

    //Id Value
    $id = "value";
    $child = $dom->createElement($id);
    $child = $occ->appendChild($child);

    //Here is the actual value
    $id = $vendor_cv[1];
    $value = $dom->createTextNode($id);
    $value = $child->appendChild($value);

    //Id text
    $id = "text";
    $child = $dom->createElement($id);
    $child = $occ->appendChild($child);

    //Here is the actual value
    $id = $vendor_cv[1];
    $value = $dom->createTextNode($id);
    $value = $child->appendChild($value);
}
//Close xml tags and save.
$xmlString = $dom->saveXML();

//Echo XML back to Transaction_Update.js
echo $xmlString;
?>

2 个答案:

答案 0 :(得分:2)

以下是如何在jQuery中执行此操作

1)在页面的head部分包含jQuery库。 (这里我是从谷歌cdn中引用它)

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>  
</head>

在你的javascript中

$("#stateDropDown").change(function(){
    var stateId=$("#stateDropDown").val();
    $.ajax({
      url: 'getcities.php?stateid='+stateId,
      success: function(data) {
       $("cityDropDown").html(data);       
      }
    });
});

假设你有一个HTML选择元素,状态为“stateDropDown”,另一个为城市的,ID为“cityDropDown”

以上代码将执行以下操作

1)当状态下拉列表的值发生变化时,它会执行内部代码。

2)重新选择所选项目值并将其存储在名为stateId的变量中。

3)使用jQuery ajax方法,它使用名为stateid的查询字符串键调用getcities.php页面

4)当我们从ajax调用获得响应时,控制流将位于名为“success”处理程序的部分中。我们在一个名为data的变量中收到响应。

5)将收到的响应(数据)设置为城市下拉列表的内部html。

假设getcities.php页面将返回一些像这样的输出

<option value='1'>Ann Arbor</option>
<option value='2'>Dexter</option>
<option value='3'>Novi</option>

jQuery将负责您的跨浏览器问题。是的,经过了充分的测试,每个人都在使用它。

http://www.jquery.com

答案 1 :(得分:0)

您可以在handleServerResponse中更改for循环以解决此问题:

for(var i=0; i < responseText.childNodes.length; i++){
    var node = responseText.childNodes[i];
    var text = node.childNodes[1].text ? node.childNodes[1].text : node.childNodes[1].textContent;
    var value = node.childNodes[0].text ? node.childNodes[0].text : node.childNodes[0].textContent;
    var newOpt = new Option(text,value);
    sel.options[sel.options.length] = newOpt;
}