简体   繁体   English

获得jQuery ajax和asp.net webmethod xml响应工作

[英]Getting jQuery ajax and asp.net webmethod xml response to work

I have an asp.net WebMethod that returns an XmlDocument object. 我有一个asp.net WebMethod,它返回一个XmlDocument对象。 I can successfully call the method using jquery ajax, but can't seem to get the function to succeed (server side webmethod gets called with correct parameters but client side method fails with 'undefined parser error'). 我可以使用jquery ajax成功调用该方法,但似乎无法使函数成功(服务器端webmethod使用正确的参数调用,但客户端方法失败并带有'undefined parser error')。

To reproduce, Asp.net C#: 重现,Asp.net C#:

[WebMethod]
public static XmlDocument test(string name)
{
    XmlDocument result = new XmlDocument();
    XmlElement root = result.CreateElement("Data");
    result.AppendChild(root);

    XmlElement element = result.CreateElement("AnElement");
    element.SetAttribute("Name", name);
    root.AppendChild(element);

    return result;
}

JavaScript: JavaScript的:

function CallForData(name) {
    $.ajax({
        type: "POST",
        url: "AppName.aspx/test",
        data: "{'name': " + name+ "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "xml",
        success: function (response) { ParseXML(response); },
        error: function (data, textStat, req) { alert(data + ' - ' + textStat + ' - ' + req); }
    });
}

If dataType: "xml" is commented out (automatic) the success function is called but the data is a load of square brackets that seem to indicate an empty json structure. 如果dataType:“xml”被注释掉(自动),则调用success函数,但数据是方括号的加载,似乎表示空的json结构。 I want an XML response that I can parse using jQuery. 我想要一个可以使用jQuery解析的XML响应。

I think I possibly need to add some format identification to the XML document but aren't sure. 我想我可能需要在XML文档中添加一些格式标识,但不确定。 Can anyone point out the problem? 任何人都可以指出这个问题吗?

Fixed by adding 通过添加修复

[System.Web.Script.Services.ScriptMethod(ResponseFormat=System.Web.Script.Services.ResponseFormat.Xml)]

to the web method. 到网络方法。

Credit to riteshtandon23 in this thread 感谢riteshtandon23在这个帖子中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM