responseText的工作,但responseXML的总是空 [英] responseText works but responseXML is always null

查看:178
本文介绍了responseText的工作,但responseXML的总是空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过每一个答案我期待在这里可以找到并解决不了这个。 我是pretty的肯定,我没有带错过了什么明显的。

我试图加载基于纬度多头地图标记。问题是,当我尝试返回Ajax响应作为responseXML的公司始终为空,如果我使用的responseText它工作正常,但很明显,下一步将无法正常工作。

这是生成XML的PHP​​:

 < PHP
标题(内容类型:文本/ XML');
?>
< XML版本=1.0编码=ISO-8859-1&GT?;
<性状>
    <![CDATA [
< PHP
如果($身体!= NULL):
        的foreach($身体为$属性):>?
        <性>
            <纬度>< PHP的echo $属性 - &GT?;土地增值税; ?>< /纬度>
            <长>< PHP的echo $属性 - &GT?;长; ?>< /长>
            <名称>< PHP的echo $属性 - > PROPERTY_NAME; ?>< /名称>
            < /性>
< PHP endforeach;
ENDIF; ?>
    ]]≥
< /性状>
 

我可以看到小提琴手的请求时确定

  

GET   /letsgo/index.php/hotmaps/get_properties_ajax/22.270888501350186/22.288560098193066/114.13720860290528/114.19827713775635   HTTP / 1.1

     

实体内容类型:文本/ XML

虽然当我看到这个在XML视图中小提琴手它似乎是空的,

这里是原始响应

  HTTP / 1.1 200 OK
日期:星期二,2013年1月15日11时04分27秒格林尼治标准​​时间
服务器:Apache / 2.4.2(Win32的)PHP / 5.4.4
的X已启动方式:PHP / 5.4.4
到期日:周四,1981年11月19日八时52分00秒格林尼治标准​​时间
缓存控制:无店面,无缓存,必重新验证,后检查= 0,pre-检查= 0
杂注:无缓存
内容长度:310
保持活动:超时= 5,最大值= 100
连接:保持活动
内容类型:text / xml的



< XML版本=1.0编码=ISO-8859-1&GT?;
<性状>
    <![CDATA [
        <性>
            <纬度> 22.2776< /纬度>
            <长> 114.173< /长>
            <名称> Kaxo塔测试< /名称>
            < /性>
        <性>
            <纬度> 22.2803< /纬度>
            <长> 114.16与LT; /长>
            <名称>久野塔< /名称>
            < /性>
    ]]≥
< /性状>
 

下面是叫每个地图上移动时产生标记功能

  //使Ajax请求
函数loadXMLDoc(下载址址){
    VAR XMLHTTP;
    如果(window.XMLHtt prequest){
        // $ C $下IE7 +,火狐,Chrome,歌剧,Safari浏览器
        XMLHTTP =新XMLHtt prequest();
      }
    其他{// code对IE6,IE5
      XMLHTTP =新的ActiveXObject(Microsoft.XMLHTTP);
      }
    xmlhttp.onreadystatechange =功能(){
      如果(xmlhttp.readyState == 4和&安培; xmlhttp.status == 200)
        {

            // VAR propertiesXml = xmlhttp.responseText; //工作正常!
            VAR propertiesXml = xmlhttp.responseXML; //总是空
            //警报(propertiesXml);
            VAR propertiesRows = propertiesXml.getElementsByTagName(物业);

            对于(VAR I = 0; I< propertiesRows.length;我++){
            VAR propertiesRow = propertiesRows [I]
            变种xmlLat = propertiesRow.getElementsByTagName(纬度)[0];
            VAR xmlLong = propertiesRow.getElementsByTagName(长)[0];
            VAR propertyLatLong =新google.maps.LatLng(parseFloat(xmlLat.firstChild.data),parseFloat(xmlLat.firstChild.data));
            //创建每个标记
            createMarker(propertyLatLong);
            }

     }
      }
    xmlhttp.open(GET,下载址址,假); //或真或假?没有什么区别
    xmlhttp.setRequestHeader(内容型,为text / xml);
    xmlhttp.send();
}
 

这是我得到的与空喂养的getElementsByTagName错误,铬控制台说:

  

未捕获的类型错误:无法调用空法的getElementsByTagName

这是在我的本地的Apache

运行

有什么建议?

/ **更新 - 工作code ** /

 <!DOCTYPE HTML>
< HTML>
  < HEAD>
    < META NAME =视CONTENT =初始规模= 1.0,用户可扩展性=无/>
    <风格类型=文本/ CSS>
      HTML {身高:100%}
      体{高度:100%;保证金:0;填充:0}
      #map_canvas {身高:100%}
    < /风格>
    <脚本类型=文/ JavaScript的SRC =htt​​ps://maps.googleapis.com/maps/api/js?key=APIKEYHERE&sensor=false>
    < / SCRIPT>

    <脚本类型=文/ JavaScript的>

      //初始化地图
      函数初始化(){

      //设置启动经纬度
      VAR myLatlng =新google.maps.LatLng(22.2776,114.173);

      //设置初始地图选项
      VAR mapOptions = {
        中心:myLatlng,
        变焦:13,
        mapTypeId:google.maps.MapTypeId.ROADMAP
        };

      //创建地图
      VAR地图=新google.maps.Map(的document.getElementById(map_canvas提供),mapOptions);

      //监听改变地图的边界 - 地图后停止移动!
      google.maps.event.addListener(地图,'闲置',函数(){
        loadByBounds(图)
        });
      }

      //如果边界已经改变
      功能loadByBounds(图){

        变种边界= map.getBounds();
        变种swPoint = bounds.getSouthWest();
        变种nePoint = bounds.getNorthEast();

        //具体合作坐标
        变种swLat = swPoint.lat();
        变种swLng = swPoint.lng();
        变种neLat = nePoint.lat();
        变种neLng = nePoint.lng();

        VAR址址=< PHP的回声SITE_URL('hotmaps / get_properties_ajax');?> /+ swLat +/+ neLat +/+ swLng +/+ neLng;

        //加载
        loadXMLDoc(下载址址,地图);

        //清晰的图标外边框

        // ....


        }

        //使Ajax请求
        函数loadXMLDoc(下载址址,地图){
            VAR XMLHTTP;
            如果(window.XMLHtt prequest){
                // $ C $下IE7 +,火狐,Chrome,歌剧,Safari浏览器
                XMLHTTP =新XMLHtt prequest();
              }
            其他{// code对IE6,IE5
              XMLHTTP =新的ActiveXObject(Microsoft.XMLHTTP);
              }
            xmlhttp.onreadystatechange =功能(){
              如果(xmlhttp.readyState == 4和&安培; xmlhttp.status == 200)
                {

                    VAR propertiesXml = xmlhttp.responseText; //工作正常!

                    //去掉开头和结尾空格(.trim()不工作)
                    propertiesXml = propertiesXml.replace(/ ^ \ S + | \ s + $ /克,'');

                    //手工解析为XML DOM对象
                    VAR分析器=新的DOMParser();
                    VAR xmlDoc中;
                       尝试 {
                            xmlDoc中= parser.parseFromString(propertiesXml,为text / xml);
                        }赶上(五){
                            警报(XML解析错误。);
                            返回false;
                        };

                    //console.log(xmlDoc);

                    //获取每个属性
                    VAR propertiesRows = xmlDoc.getElementsByTagName(物业);

                    //alert(console.log(propertiesRows));
                    对于(VAR I = 0; I< propertiesRows.length;我++){

                        VAR propertiesRow = propertiesRows [I]
                        变种xmlLat = propertiesRow.getElementsByTagName(纬度)[0];
                        VAR xmlLong = propertiesRow.getElementsByTagName(长)[0];
                        VAR propertyLatLong =新google.maps.LatLng(parseFloat(xmlLat.firstChild.data),parseFloat(xmlLong.firstChild.data));
                        //创建每个标记
                        createMarker(propertyLatLong,地图);
                    }
                 }
             }
            xmlhttp.open(GET,下载址址,假);
            xmlhttp.setRequestHeader(内容型,为text / xml);
            xmlhttp.send();
        }

        //创建新的标志物
        功能createMarker(propertyLatLong,地图){
            VAR dynamicMarker =新google.maps.Marker({

                地图:地图,
                可拖动:假的,
                位置:propertyLatLong
            });
            调试器;
        }
    < / SCRIPT>
  < /头>
  <身体的onload =初始化()>
    < D​​IV ID =map_canvas提供风格=宽度:100%;高度:100%>< / DIV>
  < /身体GT;
< / HTML>
 

解决方案

您可以尝试自己解析XML:

  VAR分析器=新的DOMParser();
VAR xmlDoc中= parser.parseFromString(xmlhttp.responseText,应用程序/ XML);
 

喜欢这一点。

I've looked through every answer i can find on here and can't solve this. I'm pretty sure I havn't missed anything obvious.

I'm trying to load map markers based on lat longs. The problem is when I try to return the AJAX response as responseXML its always null, if i use responseText it works fine but obviously the next step doesn't work.

This is the PHP that generates the XML:

<?php
header('Content-type: text/xml');
?>    
<?xml version="1.0" encoding="ISO-8859-1"?>
<properties>
    <![CDATA[
<?php 
if ($body != null): 
        foreach ($body as $property): ?>
        <property>
            <lat><?php echo $property -> lat; ?></lat>
            <long><?php echo $property -> long; ?></long>
            <name><?php echo $property -> property_name; ?></name>
            </property>
<?php endforeach;
endif; ?>
    ]]>
</properties>

I can see in Fiddler that the request is made ok

GET /letsgo/index.php/hotmaps/get_properties_ajax/22.270888501350186/22.288560098193066/114.13720860290528/114.19827713775635 HTTP/1.1

Entity Content-type: text/xml

Although when i view this in XML view in fiddler it appears to be empty,

here is the raw response

HTTP/1.1 200 OK
Date: Tue, 15 Jan 2013 11:04:27 GMT
Server: Apache/2.4.2 (Win32) PHP/5.4.4
X-Powered-By: PHP/5.4.4
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 310
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/xml



<?xml version="1.0" encoding="ISO-8859-1"?>
<properties>
    <![CDATA[
        <property>
            <lat>22.2776</lat>
            <long>114.173</long>
            <name>Kaxo Tower test</name>
            </property>
        <property>
            <lat>22.2803</lat>
            <long>114.16</long>
            <name>Kuno Tower</name>
            </property>
    ]]>
</properties>

Here is the create marker function that is called every time the map is moved

// make the ajax request
function loadXMLDoc(downUrl){
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
      }
    else {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {

            //var propertiesXml = xmlhttp.responseText; // WORKS FINE!!
            var propertiesXml = xmlhttp.responseXML; // ALWAYS null
            //alert(propertiesXml);     
            var propertiesRows = propertiesXml.getElementsByTagName("property");

            for (var i = 0; i < propertiesRows.length; i++) {           
            var propertiesRow = propertiesRows[i];
            var xmlLat = propertiesRow.getElementsByTagName("lat")[0];
            var xmlLong = propertiesRow.getElementsByTagName("long")[0];
            var propertyLatLong = new google.maps.LatLng(parseFloat(xmlLat.firstChild.data),parseFloat(xmlLat.firstChild.data));            
            // create each marker
            createMarker(propertyLatLong);
            }   

        }
      }
    xmlhttp.open("GET", downUrl, false); // false or true? makes no difference
    xmlhttp.setRequestHeader("Content-type", "text/xml");
    xmlhttp.send(); 
}

and this is the error i get for feeding getElementsByTagName with null, Chrome console says

Uncaught TypeError: Cannot call method 'getElementsByTagName' of null

This is running on my local Apache

Any suggestions?

/** UPDATE - WORKING CODE **/

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map_canvas { height: 100% }
    </style>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=APIKEYHERE&sensor=false">
    </script>

    <script type="text/javascript">  

      // initialise map 
      function initialize() {

      // set starting latlong
      var myLatlng = new google.maps.LatLng(22.2776, 114.173); 

      // set initial map options        
      var mapOptions = {
        center: myLatlng,
        zoom: 13,
        mapTypeId: google.maps.MapTypeId.ROADMAP
        };

      // create the map                       
      var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 

      // listen for changes in map bounds - after map has stopped moving!!      
      google.maps.event.addListener(map,'idle', function () {      
        loadByBounds(map);          
        });                 
      }

      // if the bounds have changed 
      function loadByBounds(map) {  

        var bounds = map.getBounds();       
        var swPoint = bounds.getSouthWest();
        var nePoint = bounds.getNorthEast();

        // specific co ordinates
        var swLat = swPoint.lat();
        var swLng = swPoint.lng();
        var neLat = nePoint.lat();
        var neLng = nePoint.lng();               

        var downUrl = "<?php echo site_url('hotmaps/get_properties_ajax'); ?>/"+swLat+"/"+neLat+"/"+swLng+"/"+neLng;

        // load the 
        loadXMLDoc(downUrl, map); 

        // clear icons outside of bounding box

        //....


        }

        // make the ajax request
        function loadXMLDoc(downUrl, map){
            var xmlhttp;
            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
              }
            else {// code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
              }
            xmlhttp.onreadystatechange=function() {
              if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {

                    var propertiesXml = xmlhttp.responseText; // WORKS FINE!!

                    // remove whitespaces from start and end (.trim() doesnt work)
                    propertiesXml = propertiesXml.replace(/^\s+|\s+$/g,'');                 

                    // manually parse to XML DOM object 
                    var parser = new DOMParser();                   
                    var xmlDoc;                 
                       try {
                            xmlDoc = parser.parseFromString (propertiesXml, "text/xml");
                        } catch (e) {
                            alert ("XML parsing error.");
                            return false;
                        };

                    //console.log(xmlDoc);

                    // get each property
                    var propertiesRows = xmlDoc.getElementsByTagName("property");   

                    //alert(console.log(propertiesRows));   
                    for (var i = 0; i < propertiesRows.length; i++) {

                        var propertiesRow = propertiesRows[i];
                        var xmlLat = propertiesRow.getElementsByTagName("lat")[0];
                        var xmlLong = propertiesRow.getElementsByTagName("long")[0];
                        var propertyLatLong = new google.maps.LatLng(parseFloat(xmlLat.firstChild.data),parseFloat(xmlLong.firstChild.data));           
                        // create each marker
                        createMarker(propertyLatLong, map);
                    }
                 }
             }
            xmlhttp.open("GET", downUrl, false);
            xmlhttp.setRequestHeader("Content-type", "text/xml");
            xmlhttp.send(); 
        }   

        // create new markers
        function createMarker(propertyLatLong, map){             
            var dynamicMarker = new google.maps.Marker({

                map:map,
                draggable:false,
                position: propertyLatLong
            });
            debugger;           
        }       
    </script>
  </head>
  <body onload="initialize()">      
    <div id="map_canvas" style="width:100%; height:100%"></div>
  </body>
</html>

解决方案

You can try parsing XML yourself:

var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlhttp.responseText, "application/xml");

Like this.

这篇关于responseText的工作,但responseXML的总是空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆