Skip to content

Instantly share code, notes, and snippets.

@craveytrain
Created February 8, 2012 02:04
Show Gist options
  • Select an option

  • Save craveytrain/1764347 to your computer and use it in GitHub Desktop.

Select an option

Save craveytrain/1764347 to your computer and use it in GitHub Desktop.
var callback = context.HttpContext.Request.QueryString.AllKeys.FirstOrDefault(k => k == "callback");
var data = "{ "key": "value" }"; // JSON payload
if(string.IsNullOrEmpty(callback))
{
response.ContentType = "application/json";
response.AddHeader("Access-Control-Allow-Origin", "*";
response.Write(data);
}
else
{
response.ContentType = "application/javascript";
response.Write(string.Format("{0}({1});",context.HttpContext.Request.QueryString[callback],data));
}
var xhr = $.ajax({
url: 'http://url.to/service',
data: { prop: 'data' },
dataType: $.support.cors ? 'json' : 'jsonp'
});
xhr.done(successCallback);
// This sets it globally so you don't have to think about it any more.
// If request is cross domain and cors is not supported, request as jsonp
$.ajaxPrefilter('json', function(options, orig, jqXHR) {
if( options.crossDomain && !$.support.cors ){
return 'jsonp';
}
});
var xhr = $.ajax({
url: 'http://url.to/service',
data: { prop: 'data' },
dataType: 'json'
});
xhr.done(successCallback);
if request has param 'callback'
set header "ContentType" = "application/javascript"
return {callback}(data)
else
set header "ContentType" = "application/json"
set header "Access-Control-Allow-Origin" = "*" (or your specific origin)
return data
@pierceray
Copy link
Copy Markdown

So are the one-off.js and the reusable.js essentially accomplishing the same thing?

@craveytrain
Copy link
Copy Markdown
Author

craveytrain commented Feb 8, 2012 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment