Creating Cross-domain Ajax Requests

Sometimes you need to create an AJAX request to an external domain url. Here’s how to do that.

Sometimes you need to create an AJAX request to an external domain url, which is not possible by standard means.

To create the request we will call the following function:

function crossDomainAJAX(url, callback) {
var headID = document.getElementsByTagName(”head”)[0];
var newRequest = document.createElement(’script’);

newRequest.type = ‘text/javascript’;
newRequest.language = ‘javascript’;

var schar; if (sInStr(url, “?”)==-1) { schar=”?”; } else { schar=”&”; }

newRequest.src = url + schar + ‘callback=’ + callback;

headID.appendChild(newRequest);
}

When sending the data back from the server at the external domain, we will use a function similar to this (ASP.NET VB):

Public Sub ExecuteCallback(ByVal res As String, ByVal callback As String)
Response.Write(callback & “(’” & res & “‘);”)
End Sub 

IMPORTANT: In order to successfuly run the JavaScript function, you’ll need these two auxiliary string functions:

function sMid(str, start, len) { if (start < 0 || len < 0) return “”; var iEnd, iLen = String(str).length; if (start + len > iLen) iEnd = iLen; else iEnd = start + len; return String(str).substring(start,iEnd); }
function sInStr(strSearch, charSearchFor, start) { if (!start) start=0; for (i=start; i < strSearch.length; i++) { if (charSearchFor == sMid(strSearch, i, charSearchFor.length)) {return i;} } return -1; }

Good Luck!

Leave Your Response