Search code examples
javascriptjsonp

JSONP questions


I'm writing some javascript that uses jQuery to make a webservice call.

  • The webservice is one that I've written (in C#), so I have full control over it.
  • The webservice is writing some values to a database.
  • The web service is not on the same domain as the web site
  • The web service takes a JSON.stringified parameter that contains all the values to commit

I have a couple of questions:

  1. If the webservice throws an exception (e.g. primary key constraint) will this cause a jQuery Ajax exception?

  2. If I want to return a value, say the number of rows affected, do I have to use JSONP (because it is cross-domain)?

Update: I have to support IE8, so CORS isn't an option. Thanks to @Volodymyr and @mcv for pointing out that option


Solution

    1. It depends how its done in c#, if it throws exception and response code would not be 200 then yes you will have error in jquery Ajax and you can add event for error, if c# doesnot throw exception then it will be success event on jquery, but probably you will got different response json with status. Since you have full control then you can do what you want.
    2. Still if you have control you can do following

      public class AllowCrossSiteAttribute : ActionFilterAttribute {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
          if (actionExecutedContext.Response != null) {
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            base.OnActionExecuted(actionExecutedContext);
          }
        }
      }
      

    Add this to you code (Please not that here you allow all domain but you can replace "*" with list of your domains), then on web api controller add this as attribute

    Or using web config

    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Headers" value="Content-Type, Authorization" />
          <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
        </customHeaders>
      </httpProtocol>
    </system.webServer>