简体   繁体   中英

JQuery Ajax Getting Response, but Always invoking Error function JSONP

I have a HttpListenerContext class, that always listen to port 13001. when ever an ajax call comes I am passing data as follows

context.Response.Close(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject("jsonp({'Status':'Good'})")), false);

Next I am invoking that Server by using Jquery ajax as follows

  $.ajax({
        url: "http://localhost:<13001>/hit/number',
        type: "GET",
        async: false,
        contentType: "application/json",
        dataType: "jsonp",
        jsonp: "jsonp",

        success: function (data, textStatus, xhr) {
            console.log(data);
        },

        error: function (xhr, ajaxOptions, thrownError) {
            console.log("Error");
        }
  });

Ajax Get Request getting Success, I am able to see the response in Chrome Network->Response Tab as follows

"jsonp({"Status":"Good"})"

But I can't get this message in Ajax Success function. It's always displaying error. Can any one please tell me where I did mistake.

Response Headers

Access-Control-Allow-Origin:*
Cache-Control:private
Content-Length:23
Content-Type:application/javascript
Date:Fri, 27 Sep 2013 01:12:25 GMT
Server:Microsoft-HTTPAPI/2.0

My gut tells me that you are not passing back a full HttpResponse. You are just passing back a text string. Since it isn't a valid HttpResponse jQuery is going to think it failed.

Solution: try adding context.Response.StatusCode = 200; this before you send the response. You might need to add a content-type as well to the response.

 context.Response.StatusCode = 200;                
 context.Response.Close(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject("jsonp({'Status':'Good'})")), false);

Same issue I have faced with oData service, its fixed by by adding the "$callback" keyword by end of the url. So the ajax URL will be like https://example.com/ApplicationData.svc/Products ?$format=json&$callback=?

courtesy : http://www.kendoui.com/blogs/teamblog/posts/11-08-24/cross-domain_queries_to_odata_services_with_jquery.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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