2011-03-13 37 views
1

腳本通過jquery.ajax獲取XML數據

$.ajax({ 
    type: "post", 
    url: "Default.aspx?cmd=Setting", 
    success: parseXml 
    }); 

function parseXml(xml) 
{ 
    alert(xml);//show Full XML File 
    //find every Tutorial and print the author 
    $(xml).find("Tutorial").each(function() 
    { 
    $("#a").append($(this).attr("author") + "<br />"); 
    }); 
} 

HTML

<div id="a"></div> 

代碼

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (Request["cmd"] == "Setting") 
    { 
     string [email protected]"<?xml version='1.0' encoding='utf-8' ?> 
     <RecentTutorials> 
     <Tutorial author='The Reddest'> 
     <Title>Silverlight and the Netflix API</Title> 
     <Categories> 
       <Category>Tutorials</Category> 
       <Category>Silverlight 2.0</Category> 
       <Category>Silverlight</Category> 
       <Category>C#</Category> 
       <Category>XAML</Category> 
     </Categories> 
     <Date>1/13/2009</Date> 
     </Tutorial> 
     </RecentTutorials>"; 

      Response.Write(k); 
      Response.End(); 
    } 
} 

我是一個初學者。

這不起作用。

while alert(xml)show xml File。

+0

請定義「不工作」。 –

+0

您是否嘗試過'alert(xml);''parseXml'內部 –

+0

show xml但不會附加到div – beginner

回答

0

嘗試迫使數據類型爲XML:dataType: 'xml'

+1

因此,您應該另外使用'Response.ContentType =「text/xml; charset = utf-8」;'在服務器代碼中 – Oleg

1

纔能有jQuery的自動解析XML設置你的服務器上的適當內容類型:

Response.ContentType = "text/xml"; 
Response.Write(k); 
Response.End(); 

此外,您可以設置dataType: 'xml'但是這不是必要的如果您的服務器已正確配置爲發送正確的內容類型。

這是live demo