本文介绍了解析XML JQuery的Ajax响应与命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我执行使用JQuery Web服务调用,它的AJAX功能,我无法分析回来的数据。当我提醒数据(警报($(数据).find(回归)。文字()),它是空的。我看到服务器使用XML数据响应如下所述,当我提醒(数据)我收到[对象的XMLDocument ]是TXT = $(数据).find(回归)。text()的有效给我的XML结构下面命名空间?我可以看到萤火虫完整的XML字符串。任何想法?

变种的txt = $(数据).find(NS1 \:回归)文本();适用于Chrome和Firefox,但不是Safari浏览器

index.js:

  $(函数(){
$阿贾克斯({
                网址:网址,
                成功:功能(数据){
                    VAR NDX = 0,
                        行,
                        ** TXT = $(数据).find(回归)。text()的,**
                        XML =反向转义(TXT),
                        xmlDoc中= $ .parseXML(XML),
                        FIRSTROW = $(xmlDoc中).find(
                                结果),儿童(:第一)。

                    //基于由返回的结果填充该表
                    // Web服务
                    $(table.results THEAD)空()。
                    $(table.results TBODY)空();
                    行= $(< TR />中);

                    row.append($(百分位/>中。)文本(#)addClass(NDX));
                    firstrow.children()。每个(函数(){
                        row.append($(百分位/>中。)文本(this.nodeName));
                    });
                    row.appendTo($(table.results THEAD));

                    $(xmlDoc中).find(行)。每个(函数(){
                        行= $(< TR />中);
                        row.append($(< TD />中。)文本(NDX + 1).addClass(NDX));
                        $(本)。儿童()。每个(函数(){
                            row.append($(< TD />中。)文本($(本)的.text()));
                        });
                        row.appendTo($(table.results TBODY));
                        NDX ++;
                    });

                    //清表,如果没有结果返回
                    如果(NDX == 0){
                        //返回任何行
                        $(table.results THEAD)空()。
                        $(table.results TBODY)空();
                    }

                    statusNotice(返回的记录:NDX +);
                },
                错误:函数(XMLHtt prequest,textStatus,errorThrown){
                    //显示由Web服务返回的错误
                    VAR xmlDoc中= $(XMLHtt prequest.responseXML);
                    statusError(xmlDoc.find(文本)文本());
                },
                完成:功能(XMLHtt prequest,textStatus){
                    //隐藏忙对话框
                    $(#忙DLG)对话框(亲密)。
                }
            });
       });
 

index.html的:                    演示            

 <脚本类型=文/ JavaScript的SRC =JS / jQuery的-1.6.4.min.js>< / SCRIPT>
<脚本类型=文/ JavaScript的SRC =JS / jQuery的-UI-min.js>< / SCRIPT>
<脚本类型=文/ JavaScript的SRC =JS / jquery.layout-latest.js>< / SCRIPT>
<脚本类型=文/ JavaScript的SRC =JS / index.js>< / SCRIPT>
< /头>
<身体GT;
//表中显示来自AJAX调用此结果
< /身体GT;
< / HTML>
 

XML:

 < NS1:executeResponse的xmlns:NS1 =htt​​p://sqlws.test.com>
< NS1:回归>
    <结果>
        <排>
            < ATTRIBUTE1>值1< / ATTRIBUTE1>
            < attribute2>值2< / attribute2>
        < /行>
        <排>
            < ATTRIBUTE1>值1< / ATTRIBUTE1>
            < attribute2>值2< / attribute2>
        < /行>
    < /结果>
< / NS1:回归>
< / NS1:executeResponse>
 

解决方案

当一个元素prefixed一个命名空间,您有无也添加命名空间:

  • .find('NS1:回归')不起作用,因为使用的jQuery伪-selectors。
  • .find('NS1 \:回归')也不起作用,因为在字符串中的单反斜线用作转义字符。 NS1 \:回归变成。NS1:回归这等于previous一个
  • .find('NS1 \\:回报') 应使用。双反斜线可用于转义冒号。

看来,最后的解决办法正常工作在IE和Firefox,但不是Opera,Chrome或Safari浏览器。为了获得最大的兼容性,使用jQuery选择器与和无假货preFIX,即。 NS1 \\:回归,回归,而不是一个简单的 NS1 \\:返回

演示: http://jsfiddle.net/5BQjv/51/

  //例如,这是结果:
VAR数据='< NS1:executeResponse的xmlns:NS1 =htt​​p://sqlws.test.com> +
               '< NS1:回归> +
                   <结果> <排> ...< /行> < /结果> +
               '< / NS1:回归> +
           '< / NS1:executeResponse>';

//的第一件事是解析字符串XML。不晚!
变量$ xmlDoc中= $($ parseXML(数据)。);

//然后,寻找与命名空间中的元素:
变量$ TXT = $ xmlDoc.find('NS1 \\:回报率,回报);

//无需使用反向转义或东西,只需使用DOM操作:
//`results`是直接子。不要使用.find,但是。儿童
变量$ FIRSTROW = $ txt.children(结果)的孩子。(:第一);
 

正如你可能已经注意到,我有prefixed一些变量与一个美元符号。这是该公约不适用于涉及jQuery的对象,一个美元符号,以避免开发过程后/混淆preFIX变量。

I'm executing a web service call using JQuery and it's ajax function and I'm unable to parse the data coming back. When I alert the data (alert($(data).find("return").text()) its empty. I see the server responding with xml data as outlined below and when I alert(data) I get [object XMLDocument]. Is txt = $(data).find("return").text() valid given my XML structure with a namespace below? I can see the full xml string in firebug. Any ideas?

var txt = $(data).find("ns1\:return").text(); works on Chrome and Firefox, but not Safari

index.js:

$(function () {
$.ajax({
                url: url,
                success: function (data) {
                    var ndx = 0,
                        row,
                        **txt = $(data).find("return").text(),**
                        xml = unescape(txt),
                        xmlDoc = $.parseXML(xml),
                        firstrow = $(xmlDoc).find(
                                "results").children(":first");

                    // populate the table based on the results returned by
                    // the web service
                    $("table.results thead").empty();
                    $("table.results tbody").empty();
                    row = $("<tr/>");

                    row.append($("<th/>").text("#").addClass("ndx"));
                    firstrow.children().each(function () {
                        row.append($("<th/>").text(this.nodeName));
                    });
                    row.appendTo($("table.results thead"));

                    $(xmlDoc).find("row").each(function () {
                        row = $("<tr/>");
                        row.append($("<td/>").text(ndx + 1).addClass("ndx"));
                        $(this).children().each(function () {
                            row.append($("<td/>").text($(this).text()));
                        });
                        row.appendTo($("table.results tbody"));
                        ndx++;
                    });

                    // clear the table if no results were returned
                    if (ndx == 0) {
                        // no rows returned
                        $("table.results thead").empty();
                        $("table.results tbody").empty();
                    }

                    statusNotice("Records Returned: " + ndx);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    // display the error returned by the web service
                    var xmlDoc = $(XMLHttpRequest.responseXML);
                    statusError(xmlDoc.find("Text").text());
                },
                complete: function(XMLHttpRequest, textStatus) {
                    // hide the busy dialog
                    $("#busy-dlg").dialog("close");
                }
            });
       });

index.html: Demo

<script type="text/javascript" src="js/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-min.js"></script>
<script type="text/javascript" src="js/jquery.layout-latest.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
//table displaying results from ajax call here
</body>
</html>

XML:

<ns1:executeResponse xmlns:ns1="http://sqlws.test.com">
<ns1:return>
    <results>
        <row>
            <attribute1>value1</attribute1>
            <attribute2>value2</attribute2>
        </row>
        <row>
            <attribute1>value1</attribute1>
            <attribute2>value2</attribute2>
        </row>
    </results>
</ns1:return>
</ns1:executeResponse>
解决方案

When an element is prefixed by a namespace, you have to also add the namespace:

  • .find('ns1:return') does not work, because : is used by jQuery as pseudo-selectors.
  • .find('ns1\:return') does not work either, because a single backslash in a string is used as an escape character. "ns1\:return" becomes "ns1:return" which is equal to the previous one.
  • .find('ns1\\:return') should be used. The double backslash is used to escape the colon.

It appears that the last solution works fine in IE and Firefox, but not Opera, Chrome or Safari. To get maximum compatibility, use jQuery selectors with, and without fake prefix, ie. "ns1\\:return, return" instead of a plain ns1\\:return.

Demo: http://jsfiddle.net/5BQjv/51/

// For example, this is the result:
var data = '<ns1:executeResponse xmlns:ns1="http://sqlws.test.com">' +
               '<ns1:return>' +
                   '<results> <row> ... </row> </results>' +
               '</ns1:return>' +
           '</ns1:executeResponse>';

// The very first thing is to parse the string as XML. NOT later!
var $xmlDoc = $($.parseXML(data));

// Then, look for the element with the namespace:
var $txt = $xmlDoc.find('ns1\\:return, return');

// No need to use unescape or something, just use DOM manipulation:
// `results` is the immediate child. Don't use .find, but .children
var $firstrow = $txt.children("results").children(":first");

As you may have noticed, I have prefixed some variables with a dollar sign. It's the convention to prefix variables which refer to jQuery objects with a dollar sign, to avoid confusion during/after development.

这篇关于解析XML JQuery的Ajax响应与命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-21 23:57