How to get clean/pure HTML from ASMX web service call

青春壹個敷衍的年華 提交于 2019-12-21 06:59:40

问题


I am trying to use jQuery .load() to get straight html from a asmx web service:

$('#target').load('MyService.asmx/GetHtml');

In .NET code, GetHtml() returns as string:

    [WebMethod(EnableSession = false)]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Xml)]
    public string GetHtml()
    {
        return "<span>Hi</span>";
    }

That returns:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">&lt;span&gt;Hi&lt;/span&gt;</string>

Notice that the string is encoded. With that encoding, $.load doesn't work right. The displayed text actually has the tags shown.

How can I get the WebMethod call to return just this?

<span>Hi</span>

回答1:


I'm pretty sure that if you want straight HTML back from a service, you would need to use a handler (.ashx) rather than .asmx. I don't know of a way to get .asmx not to encode your data in some format (though you can change what that format is).

That said, @Randolpho also has a good point.




回答2:


How about this:

Instead of pulling HTML from the service, pull data, then use jquery to insert that data into the DOM.

Then you won't have to XML decode your HTML.




回答3:


The short answer (as other posters have suggested) is: don't do that. Return JSON and use JS to craft it into the desired HTML. See this discussion for more details/comments.

However, if you have no choice but to return HTML (maybe your project mgr/architect is afraid of true webservice design, for some reason), I agree with Jake T's answer here: use ajax to call an ASPX page.

ASPX's whole purpose in life is to return HTML (unlike ASMX or ASHX). Most importantly, well-written ASPX separates the HTML from the logic/codebehind. That way, when you need to change the HTML from a list to a table (or whatever) you can do so without re-compiling, re-testing, and re-deploying the whole darn system! :)




回答4:


The simplest way is to not use a web service at all. An HTTP request with a response containing HTML is basically the most common operation that happens on the web so the default tools are designed to do that. In the case of asp.net that would be an aspx file.



来源:https://stackoverflow.com/questions/3919243/how-to-get-clean-pure-html-from-asmx-web-service-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!