Cross Domain AJAX Requests(XMLHttpRequests) Using Dojo's ScriptSrcIO and JSON
Due to browser security restriction, one can't make AJAX request to domains other than the domain that the Javascript was originally downloaded from.
But you can still do cross-domain AJAX requests because dynamic cross-domain loading of scripts is allowed. It's very easy to do that via Dojo's ScriptSrcIO and JSON because.
Dojo's Wiki has all the details for the client-side Javascript implementation. But the instruction leaves out a critical piece: what's expected out of the server-side service.
Let me complete the picture.
Here's an example of client-side implmentation:
dojo.require(”dojo.io.*”);
dojo.require(”dojo.io.ScriptSrcIO”);
dojo.io.bind({
url: finalURL,
checkString: "taskLoaded", //This means (typeof(taskLoaded) != undefined) indicates that the script loaded.
transport: "ScriptSrcTransport",
jsonParamName: "jCallBack",
content: {
json: jsonString
},
mimetype: "text/json",
load: function(type, data, event, kwArgs) {
// data is converted into an object automatically by Dojo
// in this case, the JSON object has a element called message
alert("message " + data.message);
},
error: function(type, data, event, kwArgs) {
alert("error");
},
timeout: function() { alert("time out");},
timeoutSeconds: 5
});
Here's an example of server-side service implementation in Java
String jsonRequestStr = request.getParameter("json");
// convert jsonRequestStr to an JSON object
// do something with it
...
...
// create the response json object "jsonResponseObj"
...
...
// convert it back to JSON string. responseText must be a string in valid JSON format
String responseText = jsonResponseObj.toString();
// jsonCallBack is the value for jsonParamName in the ScriptSrcTransport request
String jsCallBackFunction= request.getParameter("jCallBack");
str = jsCallBackFunction + "(" + responseText + ");";
response.setContentType("application/x-json");
response.getWriter().print(str);
response.getWriter().flush();
The basic idea is that the server needs to respond with a string that's a valid Javascript function call. It gets the name of the function to be called back from the "jsonParamName" request parameter, and passes your JSON response string to the callback function. When Dojo receives the string, it automatically converts the response text(JSON text) into a object and passed it to your "load" function.
One last word on converting Javascript objects to JSON strings: Don't use json.js from json.org to convert JavaScript objects to JSON strings because it conflicts with Dojo's ScriptSrcTransport(I use Dojo 0.3.1). The error is
dojo.js (line 455) state.kwArgs has no properties
You should use Dojo's json.serialize function instead:
dojo.require("dojo.json");
var jsonString = dojo.json.serialize(requestObj);
Tags: dojo ajax javascript











