通过jquery.ajax获取xml数据

时间:2011-03-13 07:53:11

标签: asp.net xml jquery xmlhttprequest

脚本

  $.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 k=@"<?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)显示xml文件。

2 个答案:

答案 0 :(得分:1)

在服务器上设置正确的内容类型,以便让jQuery自动解析XML:

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

此外,您可以设置dataType: 'xml',但如果您的服务器已正确配置为发送正确的内容类型,则无需设置。

这是live demo

答案 1 :(得分:0)

尝试将dataType强制转换为xml:dataType: 'xml'