IT:AD:JScript:AJAX
CheckList
Recap
- Ajax stands for Async Javascript Xml.
- the name says it all:
$.ajaxwill always be using async calls- hence always needs a success callback defined
* Under the hood it is using
XMLHttpRequest
- Communication is usually in JSON, POX, or scalar.
- Most modern browsers won't allow cross browser.
- Unless you specify
dataType="jsonp"
- Request Attributes:
Content-Type: Defines format of what is being sent.Accept: defines format expected back
.NET Attributes
To get AJAX to work in ASP.NET, you definately need a couple of Attributes added to your code. These are covered here:
Syntax
Async, basic example, success callback:
$.ajax({url:myUrl,success:function(r){MyMethod(r);}});
Async,
$.ajax(
{
type:"POST",
dataType:"json",
contenType:"application/json",
url: "somehting.asmx/method",
data: "{'id:'"+id+"'}",
success:function(data){alert (data.d)},
error: myErrorHandler
});
function myErrHandler(jqXHR, textStatus, errorThrown){...}
* $.post
- A shorthand version of ajax
- Use this rather than $.get If the target is a WebService that is not decorated with
ScriptMethodAttrbute.
$.post({url:myUrl,function(r){MyMethod(r);});
* $.get
- A shorthand version of ajax
* $.getJSON
- A shorthand version of ajax
* $.getScript
- A shorthand version of ajax
Cross Script Solutions
Proxy
The first solution is to use a server side proxy to the the remote Service.
Client->$.ajax(..)->proxy.php->OtherSite... $url = 'http://othersite.com/someservice?' . http_build_query($_GET); echo file_get_contents($url);
* Pros:
- Gets around issue
* Cons:
- Uses server resources
- more config
JSONP
The second solution is to use JSON with Padding.
Basically works by getting around XSS by injecting the request into the dom.
The server has to be JSONP ready, and look for the well-known jsoncallback value which will contain the script name to invoke when it gets back.
$.getJSON(
"http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "jquery",
tagmode: "any",
format: "json"
},
function(data) {...}
);
Note that the question mark is regex/replaced with the randomly named callback.
Here is an example calling Twitter:
$(document).ready(function() {
$.getJSON('http://twitter.com/users/usejquery.json?callback=?', function(json) { //get information about the user usejquery from twitter api
$('#twitter_followers').text(json.followers_count); //get the follower_count from the json object and put it in a span
});
});
The way to prepare the results on the MVC side of things, was described here
public class JsonpResult : System.Web.Mvc.JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
context.ValidateIsNotNull("context");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = (!String.IsNullOrEmpty(ContentType))
? ContentType: "application/javascript";
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
// The JavaScriptSerializer type was marked as obsolete prior to .NET Framework 3.5 SP1
#pragma warning disable 0618
HttpRequestBase request = context.HttpContext.Request;
JavaScriptSerializer serializer = new JavaScriptSerializer();
response.Write(request.Params["jsoncallback"] + "(" + serializer.Serialize(Data) + ")");
#pragma warning restore 0618
}
}
}