Tony
Tony

Reputation: 11

jQuery and cross domain with jsonp - please help

I am trying out jsonp with jQuery. I found many examples on the web and I believe my code is correct, but its still not working for me.

My web service:

using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.Script.Serialization;

namespace App_Code
{
    /// <summary>
    /// Summary description for WebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/", Name = "WebService")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [ScriptService]
    public class WebService : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public string GetAd()
        {
            var json = new JavaScriptSerializer().Serialize(new
            {
                Prop1 = "some property",
            });
            string callback = HttpContext.Current.Request["callback"];
            return string.Format("{0}({1})", callback, json);
        }
    }
}

Client-side:

$(document).ready(function () {
    alert('Loading...');

    $.ajax({ url: 'http://mediaserver/WebService.asmx/GetAd?callback?',
        data: {},
        success: function (json) {
            alert(json);
        }
    });
});

Firebug shows this is a success, but I am getting null from the alert. I have my webservice in iis7 locally and I am testing through my debug in my client project.

I need to get cross-domain working.

Please help.

Upvotes: 1

Views: 1324

Answers (2)

Chase Florell
Chase Florell

Reputation: 47367

You've got two question marks in your url http://mediaserver/WebService.asmx/GetAd?callback?

My thoughts would be that it needs to be

$(document).ready(function () {
    alert('Loading...');

    $.ajax({ url: 'http://mediaserver/WebService.asmx/GetAd?callback=',
        data: {},
        success: function (json) {
            alert(json);
        }
    });
});

Upvotes: 1

Jan Zyka
Jan Zyka

Reputation: 17898

I think you are missing = in the URL. The callback should have the = (at least it works like this for me). First line would be:

$.ajax({ url: 'http://mediaserver/WebService.asmx/GetAd?callback=?'
...

Also you are not specifying you want JSON, either use dataType: 'json' in the ajax request or go directly with $.getJSON (doc). Not sure of jQuery is capable of autodetecting JSONP. This might not be causing the bug though.

Upvotes: 0

Related Questions