If you want to have your web method working in JSON mode
you have to apply [ScriptService] attribute to your web service class.
Vinija, thanks for your suggestion (I should have included more code in my example). I am in fact using the [ScriptService] attribute in my web service class, but it has no effect -- when I browse tohttp://localhost:49526/trunk/WebServiceTest.asmx/HelloWorld, I still see the following result:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">Hello world!</string>
I'm not familiar with the Yahoo API, but to be able to use this with a <script> tag, you'll need to use something called "JSON-P" or "JSON with Padding". Basically that returns a string that looks like: "callback('Hello world!');" It's the JSON-encoded return value of your web service wrapped in parentheses and prepended with a callback name. That way you can implement a function on the page called "callback" and get passed the result of the web service call.
ASP.NET AJAX can be used to use an HTTP GET (see the ScriptMethod attribute for configuring HTTP GET versus POST) to retrieve a JSON-encoded string, but it doesn't currently wrap it for you with a callback method.
I think the simplest thing for you to do is to build your own handler, and just do something like:
Response.Write(string.Format("callback({0});", new JavaScriptSerializer().Serialize("Hello, World!")));
I just realized that "build your own handler" sounds scary... I just mean a .ashx. I'm basically suggesting thatinstead of a web service.
Well, there is nothing wrong with seeing XML tags on the response however you can also do
the following.
1. In your page's script manager add reference to your web service
(This should be included inside your scriptmanager tag : <asp:ServiceReference Path="~\YourService.asmx" /> )
2. Call yor web method from your page's client side <YourService>.<YourMethodName>(<yourparameter>,onSuccess, onError)
while onSuccess and onError are two callbacs invoked on seccess / error respectively.
3. At your onSeccuss function you can do the following:
function onSuccess(result)
{
alert(result);
{
and the returned string will apear.
Thanks Steve, using a generic handler did the trick -- it seems to be just what I was looking for.
No comments:
Post a Comment