使用$ .ajax()过滤XML文件

时间:2012-01-04 07:49:23

标签: javascript jquery xml ajax

我正在使用以下代码查询大型(1000个节点)XML文件:

$.ajax({
                        type: "GET",
                        cache: false,
                        url: "someFile.xml",
                        dataType: "xml",
                        contentType: "text/xml",
                        success: function(xmlHttpRequest)

以及以下XML结构:

<hospitals>
  <hospital>
    <id>1</id>
    <name>H1</name>
    <city>Riyadh</city>
    <tel>1234567</tel>
    <coordinates>27.034052,49.490662</coordinates>
  </hospital>
</hospitals>

我的问题是:有没有办法过滤(例如基于城市)XML文件到位而不读取整个文件然后自己过滤?我很确定在上面的调用中有一个字段可以进行过滤,但我无法弄明白。

1 个答案:

答案 0 :(得分:0)

使用parse XML之类的

var xml = "<hospitals>\
  <hospital>\
    <id>1</id>\
    <name>H1</name>\
    <city>Riyadh</city>\
    <tel>1234567</tel>\
    <coordinates>27.034052,49.490662</coordinates>\
  </hospital>\
</hospitals>",
    xmlDoc = $.parseXML( xml ),
    $xml = $( xmlDoc ),
        $title = $xml.find( "city" ).text();

if($title=='Riyadh')
    alert($xml.find("tel").text());

http://jsfiddle.net/9JUNK/3/

或者您可以使用dataFilter过滤响应,然后在成功处理程序

中处理它
dataFilter(data, type)Function
A function to be used to handle the raw response data of XMLHttpRequest.
This is a pre-filtering function to sanitize the response.
You should return the sanitized data. The function accepts two arguments:
The raw data returned from the server and the 'dataType' parameter.