这是我的 JQuery AJAX 调用。这是在 document.ready() 函数内部。这应该是在我的 web 服务中读取 webmethod 返回的 xml 数据的那个:
$.ajax({
type: "POST",
url: "http://tempuri.org/NewsletterList.asmx/HelloWorld",
contentType: "application/xml; charset=utf-8",
dataType: "xml",
success: function (xml) {
$(xml).find('Newsletter').each(function () {
var title = $(this).find('Title').text();
var created = $(this).find('Created').text();
AddOption(title);
alert('Ywes');
});
},
error: function (msg, m2, m3) {
alert(m2);
}
});
这是我的网络服务中的网络方法调用。我能够完全成功地创建 xml,但我发现很难将 xml 返回到 ajax 调用。
[WebService(Namespace = "http://tempuri.org/")]
.
.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public XmlDocument HelloWorld()
{
//Instantiate model object
nl = new Newsletter();
//Initiate XML stuff
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
XmlWriter writer = XmlWriter.Create(sb, settings);
writer.WriteStartDocument();
writer.WriteStartElement("Root");
foreach (Newsletter nls in nl.GetNewsletterList())
{
writer.WriteStartElement("Newsletter");
writer.WriteElementString("Title", nls.Title);
writer.WriteElementString("Created", nls.Created.ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(sb.ToString());
return xmlDocument;
}