简体   繁体   English

jQuery .find()不会在IE中返回数据,但会在Firefox和Chrome中返回数据

[英]jQuery .find() doesn't return data in IE but does in Firefox and Chrome

I helped a friend out by doing a little web work for him. 我为一个朋友做了一些网络工作,帮助了他。 Part of what he needed was an easy way to change a couple pieces of text on his site. 他需要的一部分是在他的站点上更改几段文字的简便方法。 Rather than having him edit the HTML I decided to provide an XML file with the messages in it and I used jQuery to pull them out of the file and insert them into the page. 与其让他编辑HTML,我决定提供一个带有消息的XML文件,然后我使用jQuery将它们从文件中拉出并插入到页面中。

It works great... In Firefox and Chrome, not so great in IE7. 它的效果非常好...在Firefox和Chrome中,在IE7中效果不佳。 I was hoping one of you could tell me why. 我希望你们中的一个能告诉我原因。 I did a fair but of googling but couldn't find what I'm looking for. 我做了一个公平的但谷歌搜索,但找不到我想要的东西。

Here's the XML: 这是XML:

<?xml version="1.0" encoding="utf-8" ?>
<messages>
  <message type="HeaderMessage">
    This message is put up in the header area.
  </message>
  <message type="FooterMessage">
    This message is put in the lower left cell.
  </message>
</messages>

And here's my jQuery call: 这是我的jQuery调用:

<script type="text/javascript">
  $(document).ready(function() {
    $.get('messages.xml', function(d) {
      //I have confirmed that it gets to here in IE
      //and it has the xml loaded.
      //alert(d); gives me a message box with the xml text in it
      //alert($(d).find('message')); gives me "[object Object]"
      //alert($(d).find('message')[0]); gives me "undefined"
      //alert($(d).find('message').Length); gives me "undefined"
      $(d).find('message').each(function() {
        //But it never gets to here in IE
        var $msg = $(this);
        var type = $msg.attr("type");
        var message = $msg.text();
        switch (type) {
        case "HeaderMessage":
          $("#HeaderMessageDiv").html(message);
          break;
        case "FooterMessage":
          $("#footermessagecell").html(message);
          break;
          default:
        }
      });
    });
  });
</script>

Is there something I need to do differently in IE? 我需要在IE中做些不同的事情吗? Based on the message box with [object Object] I'm assumed that .find was working in IE but since I can't index into the array with [0] or check it's Length I'm guessing that means .find isn't returning any results. 基于带有[object Object]的消息框,我假定.find在IE中正常工作,但是由于我无法用[0]索引到数组或检查它的长度,所以我猜想这意味着.find不是返回任何结果。 Any reason why that would work perfectly in Firefox and Chrome but fail in IE? 有什么理由可以在Firefox和Chrome中完美运行,但在IE中失败?

I'm a total newbie with jQuery so I hope I haven't just done something stupid. 我是jQuery的新手,所以我希望自己不要做一些愚蠢的事情。 That code above was scraped out of a forum and modified to suit my needs. 上面的代码已从论坛中删除,并进行了修改以满足我的需要。 Since jQuery is cross-platform I figured I wouldn't have to deal with this mess. 由于jQuery是跨平台的,所以我认为我不必处理这种混乱情况。

Edit: I've found that if I load the page in Visual Studio 2008 and run it then it will work in IE. 编辑:我发现,如果我在Visual Studio 2008中加载页面并运行它,那么它将在IE中工作。 So it turns out it always works when run through the development web server. 因此,事实证明,在通过开发Web服务器运行时,它始终有效。 Now I'm thinking IE just doesn't like doing .find in XML loaded off of my local drive so maybe when this is on an actual web server it will work OK. 现在,我认为IE只是不喜欢从本地驱动器中加载XML格式的.find文件,因此也许当它在实际的Web服务器上运行时就可以了。

I have confirmed that it works fine when browsed from a web server. 我已经确认从网络服务器浏览时可以正常工作。 Must be a peculiarity with IE. 必须是IE的特殊功能。 I'm guessing it's because the web server sets the mime type for the xml data file transfer and without that IE doesn't parse the xml correctly. 我猜这是因为Web服务器为xml数据文件传输设置了mime类型,而没有IE则无法正确解析xml。

Since IE's problem is its xml parser chokes on xml files that are not passed down using the correct "text/xml" header, you can include a bit of code in the Ajax complete event: 由于IE的问题是未使用正确的“ text / xml”标头传递下来的xml文件的xml解析器阻塞,因此您可以在Ajax complete事件中包含一些代码:

complete: function( xhr, status )
    {
      alert( "COMPLETE.  You got:\n\n" + xhr.responseText ) ;
      if( status == 'parsererror' )
      {
        alert( "There was a PARSERERROR.  Luckily, we know how to fix that.\n\n" +
               "The complete server response text was " + xhr.responseText ) ;

        xmlDoc = null;

        // Create the xml document from the responseText string.
        // This uses the w3schools method.
        // see also
        if( window.DOMParser )
        {
          parser=new DOMParser();
          xmlDoc=parser.parseFromString( xhr.responseText,"text/xml" ) ;
        }
        else // Internet Explorer
        {
          xmlDoc=new ActiveXObject( "Microsoft.XMLDOM" ) ;
          xmlDoc.async = "false" ;
          xmlDoc.loadXML( xhr.responseText ) ;
        }

        $( '#response' ).append( '<p>complete event/xmlDoc: ' + xmlDoc + '</p>' ) ;
        $( '#response' ).append( '<p>complete event/status: ' + status + '</p>' ) ;

        processXMLDoc( xmlDoc ) ;
      }
    },

here's a more complete example 这是一个更完整的例子

<!DOCTYPE html>
<html>
<head>
<title>Reading XML with jQuery</title>
<style>
#response
{
  border: solid 1px black;
  padding: 5px;
}
</style>
<script src="jquery-1.3.2.min.js"></script>
<script>
function processXMLDoc( xmlDoc )
{
  var heading = $(xmlDoc).find('heading').text() ;
  $( '#response' ).append( '<h1>' + heading + '</h1>' ) ;

  var bodyText = $(xmlDoc).find('body').text() ;
  $( '#response' ).append( '<p>' + bodyText + '</p>' ) ;
}
$(document).ready(function()
{
  jQuery.ajax({

    type: "GET",

    url: "a.xml",  // ! watch out for same
    // origin type problems

    dataType: "xml", // 'xml' passes it through the browser's xml parser

    success: function( xmlDoc, status )
    {
      // The SUCCESS EVENT means that the xml document
      // came down from the server AND got parsed successfully
      // using the browser's own xml parsing caps.

      processXMLDoc( xmlDoc );

      // IE gets very upset when
      // the mime-type of the document that
      // gets passed down isn't text/xml.

      // If you are missing the text/xml header
      // apparently the xml parse fails,
      // and in IE you don't get to execute this function AT ALL.

    },
    complete: function( xhr, status )
    {
      alert( "COMPLETE.  You got:\n\n" + xhr.responseText ) ;
      if( status == 'parsererror' )
      {
        alert( "There was a PARSERERROR.  Luckily, we know how to fix that.\n\n" +
               "The complete server response text was " + xhr.responseText ) ;

        xmlDoc = null;

        // Create the xml document from the responseText string.
        // This uses the w3schools method.
        // see also
        if( window.DOMParser )
        {
          parser=new DOMParser();
          xmlDoc=parser.parseFromString( xhr.responseText,"text/xml" ) ;
        }
        else // Internet Explorer
        {
          xmlDoc=new ActiveXObject( "Microsoft.XMLDOM" ) ;
          xmlDoc.async = "false" ;
          xmlDoc.loadXML( xhr.responseText ) ;
        }

        $( '#response' ).append( '<p>complete event/xmlDoc: ' + xmlDoc + '</p>' ) ;
        $( '#response' ).append( '<p>complete event/status: ' + status + '</p>' ) ;

        processXMLDoc( xmlDoc ) ;
      }
    },
    error: function( xhr, status, error )
    {
      alert( 'ERROR: ' + status ) ;
      alert( xhr.responseText ) ;
    }
  });
});
</script>
</head>
<body>
  <div>
    <h1><a href="http://think2loud.com/reading-xml-with-jquery/">Reading XML with jQuery</a></h1>
    <p>
      <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options">#1 jQuery.ajax ref</a>
    </p>

  </div>

  <p>Server says:</p>
  <pre id="response">

  </pre>
</body>
</html>

contents of a.xml a.xml的内容

<?xml version="1.0"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

It extends this example . 它扩展了这个示例

Check the content type of the response. 检查响应的内容类型。 If you get messages.xml as the wrong mime type, Internet Explorer won't parse it as XML. 如果您将messages.xml设置为错误的MIME类型,则Internet Explorer不会将其解析为XML。

To check the content type, you need access to the XMLHttpRequest object. 要检查内容类型,您需要访问XMLHttpRequest对象。 The normal success callback doesn't pass it as a parameter, so you need to add a generic ajaxComplete or ajaxSuccess event handler. 正常的成功回调不会将其作为参数传递,因此您需要添加通用的ajaxComplete或ajaxSuccess事件处理程序。 The second parameter for those events is the XMLHttpRequest object. 这些事件的第二个参数是XMLHttpRequest对象。 You can call the getResponseHeader method on it to get the content type. 您可以对其调用getResponseHeader方法以获取内容类型。

$(document).ajaxComplete(function(e, x) {
    alert(x.getResponseHeader("Content-Type"));
});

Unfortunately there's no way that I know of in Internet Explorer to override what the server sends, so if it's wrong you need to change the server to send "text/xml" for the content type. 不幸的是,我在Internet Explorer中没有办法覆盖服务器发送的内容,因此,如果错误,则需要更改服务器以发送“ text / xml”作为内容类型。

Some browsers have a overrideMimeType method that you can call before send to force it to use "text/xml", but Internet Explorer doesn't support that as far as I know. 某些浏览器具有您可以在send之前调用它的overrideMimeType方法,以强制它使用“ text / xml”,但是据我所知,Internet Explorer不支持该方法。

The dataType :"xml" does not fix this issue in IE8, rather it throughs a "TypeError" expection. dataType:“ xml”不能解决IE8中的此问题,而是可以满足“ TypeError”的要求。

Quick & Dirty fix, is to wrap the xml response in a html element, like div: 快速与肮脏的解决方法是将xml响应包装在html元素中,例如div:

$("<div>" + xml + "</div>").find("something");

(works in all browsers) (适用于所有浏览器)

You may find that if you pass the data type into your get call, it may parse as XML properly. 您可能会发现,如果将数据类型传递到get调用中,则它可能会正确解析为XML。 IE's quirks could stop jQuery autodetecting it as XML, resulting in the wrong data type being passed to the callback function. IE的怪癖可能会阻止jQuery自动将其检测为XML,从而导致将错误的数据类型传递给回调函数。

<script type="text/javascript">
      $(document).ready(function() {
        $.get('messages.xml', function(d) {
          //I have confirmed that it gets to here in IE
          //and it has the xml loaded.
          //alert(d); gives me a message box with the xml text in it
          //alert($(d).find('message')); gives me "[object Object]"
          //alert($(d).find('message')[0]); gives me "undefined"
          //alert($(d).find('message').Length); gives me "undefined"
          $(d).find('message').each(function() {
            //But it never gets to here in IE
            var $msg = $(this);
            var type = $msg.attr("type");
            var message = $msg.text();
            switch (type) {
            case "HeaderMessage":
              $("#HeaderMessageDiv").html(message);
              break;
            case "FooterMessage":
              $("#footermessagecell").html(message);
              break;
              default:
            }
          });
        }, "xml");
      });
</script>

EDIT: 编辑:

I have actually just experienced .find() not working for a project in any browser but I was able to use .filter() instead. 我实际上刚刚体验过.find()不能在任何浏览器中为项目工作,但是我可以使用.filter()来代替。 It's annoying that I had to resort to this but if it works.... 我不得不求助于此,但如果它可行的话,这很烦人。

$(d).filter('message').each(......);

You can do 你可以做

<a>
<messages>
  <message type="HeaderMessage">
    This message is put up in the header area.
  </message>
  <message type="FooterMessage">
    This message is put in the lower left cell.
  </message>
</messages>
</a>

and use find(). 并使用find()。 It works for IE8 and for firefox v.3.6.3 它适用于IE8和firefox v.3.6.3

I also had an same problem but I had fixed the IE jQuery XML .find() issue using below code. 我也遇到了同样的问题,但是我使用下面的代码修复了IE jQuery XML .find()问题。

Note: Use .text() instead of .html(). 注意:使用.text()而不是.html()。

jQuery.ajax({
 type: "GET",
        url: "textxml.php",
        success: function(msg){             
            data = parseXml(msg);
            //alert(data);
            var final_price = jQuery(data).find("price1").text();
            alert(final_price); 
            }
    });     

function parseXml(xml) {
     if (jQuery.browser.msie) {
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); 
        xmlDoc.loadXML(xml);
        xml = xmlDoc;
    }   
    return xml;
}

I ran into the same problem when I was retrieving data from an XML document. 当我从XML文档中检索数据时遇到了同样的问题。 After googling a lot on the Internet, I came up finding this website but with no proper answer to the issue. 在Internet上搜索了很多之后,我开始找到该网站,但没有对该问题的正确答案。 But one answer helped me solving the problem though: 但是,有一个答案可以帮助我解决问题:

"Since IE's problem is its xml parser chokes on xml files that are not passed down using the correct "text/xml" header, you can include a bit of code in the Ajax complete event:" “由于IE的问题是它的xml解析器阻塞了没有使用正确的“ text / xml”标头传递的xml文件,因此您可以在Ajax complete事件中包含一些代码:”

I have identified two problems with IE when making the $.ajax(...) and $.get(...) calls: 在进行$ .ajax(...)和$ .get(...)调用时,我发现了IE的两个问题:

  1. The xml parameter value must be in upper case ('XML' not 'xml') for both calls - $.ajax(..., dataType: "XML") and $.get(xmlDataFilePath, function(d){...}, "xml") 两次调用的xml参数值都必须为大写(“ XML”而不是“ xml”)-$ .ajax(...,dataType:“ XML”)和$ .get(xmlDataFilePath,function(d){.。 。},“ xml”)

  2. When the ajax call succeeds, the xml argument of the callback function is actually a string not an XML DOM object 当ajax调用成功时, 回调函数的xml参数实际上是一个字符串,而不是XML DOM对象

The second issue is solved this way: 第二个问题通过这种方式解决:

$(document).ready(function()
{
    $.ajax(
    { 
        type: "GET",
        url: "messages.xml", 
        dataType: "XML", /* this parameter MUST BE UPPER CASE for it to work in IE */
        success: function(xml)
        { 
            processXmlDoc( createXmlDOMObject ( xml ) );
        }, /* success: */
        error: function(xhr, textStatus, errorThrown)
        { 
            alert(textStatus + ' ' + errorThrown);
        } /* error: */
    });/* $.ajax */

    function createXmlDOMObject(xmlString)
    {
        var xmlDoc = null;

        if( ! window.DOMParser )
        {
            // the xml string cannot be directly manipulated by browsers 
            // such as Internet Explorer because they rely on an external 
            // DOM parsing framework...
            // create and load an XML document object through the DOM 
            // ActiveXObject that it can deal with
            xmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );
            xmlDoc.async = false;
            xmlDoc.loadXML( xmlString );
        }
        else
        {
            // the current browser is capable of creating its own DOM parser
            parser = new DOMParser();
            xmlDoc = parser.parseFromString( xmlString, "text/xml" ) ;
        }

        return xmlDoc;
    }

    function processXmlDoc(xmlDoc)
    {
        // write here your XML processing logic for the document object...
    } 
}); // $(document).ready

Change the following content. 更改以下内容。

dataType :"text/xml",

to

dataType :"xml",

No need to change the find(). 无需更改find​​()。

$.ajax({
  url: 'messages.xml',
  success: function(data){
     $(d).find('message').each(function(){
        //But it never gets to here in IE
        var $msg = $(this);
        var type = $msg.attr("type");
        var message = $msg.text();
        switch (type) {
          case "HeaderMessage":
             $("#HeaderMessageDiv").html(message);
          break;
          case "FooterMessage":
             $("#footermessagecell").html(message);
          break;
        }
      });
  },
  dataType: 'xml'
});

Try telling jQuery what dataType its getting so that it uses the correct methods to process your request . 尝试告诉jQuery它得到什么dataType,以便它使用正确的方法来处理您的请求。

I also had an same problem while importing email contacts. 导入电子邮件联系人时,我也遇到了同样的问题。 I was able to import contacts and display in all the browsers except in IE, as .find() was not working. 我可以导入联系人并在除IE中以外的所有浏览器中显示,因为.find()无法正常工作。

So, I assigned "text/xml" to response.contentType . 因此,我为response.contentType分配了"text/xml"

ie response.contentType = "text/xml" and it worked. response.contentType = "text/xml"并且它起作用了。

earlier it was "text/html" 之前是"text/html"

Sometimes IE reads line breaks as extra nodes. 有时IE会将换行符读取为额外的节点。 Try removing the extra white space up to the tags, or try encasing it as CDATA. 尝试删除标记之前的多余空白,或尝试将其包装为CDATA。

I had the same problem, I am developing an application which is web-based, but I need it to deploy it offline, inside a CD. 我遇到了同样的问题,我正在开发一个基于Web的应用程序,但是我需要它来离线将其部署在CD内。 I found solution in this page which is the same solution you can se above http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests and the code is very simple: 我在此页面中找到了解决方案,它与您可以在http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests上方使用的解决方案相同,并且代码非常简单:

 $.ajax({
   url: "data.xml",
   dataType: ($.browser.msie) ? "text" : "xml",
   success: function(data){
     var xml;
     if (typeof data == "string") {
       xml = new ActiveXObject("Microsoft.XMLDOM");
       xml.async = false;
       xml.loadXML(data);
     } else {
       xml = data;
     }
     // write here your XML processing logic for the document object... 
   }
 });

It's working fine!!! 运行正常!!! Try this, 尝试这个,

Chrome/Firefox: Chrome / Firefox:

xml.children[0].childNodes[1].innerHTML;

IE8+/Safari: IE8 + / Safari:

xml.childNodes[0].childNodes[1].textContent;

IE8: IE8:

xml.documentElement.childNodes[1].text;

Sample code here, 这里的示例代码

var xml = $.parseXML(XMLDOC); 

Var xmlNodeValue = ""; 

if(userAgent.match("msie 8.0")){

xmlNodeValue = xml.children[0].childNodes[1].innerHTML;

}else{ // IE8+

xmlNodeValue = xml.childNodes[0].childNodes[1].textContent; 

}

If the XML is generated by a PHP script you can do 如果XML是由PHP脚本生成的,则可以执行

<?php
    header("Content-type: text/xml");
    echo '<myxml></myxml>';
?>

Then the find method works on every browser 然后find方法可在所有浏览器上使用

I have the same problem... 我也有同样的问题...

Resolved with this : 解决此问题:

http://www.w3schools.com/dom/dom_parser.asp http://www.w3schools.com/dom/dom_parser.asp

if (window.DOMParser)
  {
  parser=new DOMParser();
  xmlDoc=parser.parseFromString(text,"text/xml");
  }
else // Internet Explorer
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
  xmlDoc.loadXML(text); 
  }

use it to transform your var to xml object... 使用它将您的var转换为xml对象...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 jQuery .find()不返回数据……在IE中 - Jquery .find() doesn't return data…in IE jQuery UI droppable在IE和Firefox上不起作用(但在Chrome上有效) - jQuery UI droppable doesn't work on IE and Firefox (but does on Chrome) jQuery模糊在Firefox和Chrome中不起作用,但在IE9中起作用 - Jquery blur doesn't work in Firefox and Chrome but works in IE9 为什么此代码在FireFox和IE中不能使用,而在Chrome中不能使用? - Why Doesn't This Code Work in FireFox and IE but does in Chrome? jQuery find()适用于IE,但不适用于Chrome或Firefox - jQuery find() works in IE, but not Chrome or Firefox jquery.ui.tabs.js不会在IE9,Chrome中加载标签数据-在Firefox中工作正常 - jquery.ui.tabs.js doesn't load tab data in IE9, Chrome - works perfectly fine in firefox jQuery $(“#id”)。html(data)不适用于Firefox,但适用于chrome - The jquery $(“#id”).html(data) does't work on firefox, but working on chrome Jquery / Javascript和Css条件在firefox和IE上不起作用。 它适用于Chrome - Jquery/Javascript and Css condition doesn't work on firefox and IE. It works on Chrome jQuery不适用于Firefox,但适用于Chrome - jQuery doesn't work on Firefox but works on Chrome Chrome不会提醒Cookie,但Firefox会提醒 - Chrome doesn't alert cookie, but Firefox does
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM