XHR has limitations. The big one is that url:
is not cross-domain: you can't submit the request outside of the current host (eg: to url:"http://google.com"
). It is a known limitation and a common mistake when getting excited about Ajax.
dojo.xhrGet
function init(){
dojo.xhrGet({
url:'ajaxServlet',
content:{param1: 'value'},
load:function(resp, ioArgs){
console.debug(resp);
}
});
}
dojo.addOnLoad(init);
Some import configurations:
url: URL to server endpoint.
load: Optional. Process what server return.
error:
Optional.When error happen, call this function.
content: Optional. Contains properties with string values. These properties will be serialized as name1=value2 and passed in the request.
handleAs:
Optional. how we handle what is coming back. Acceptable values are: text (default), json, json-comment-optional, json-comment-filtered, javascript, xml.返回的数据如何处理
form: the form to submit.(url和form二选一)
preventCache: Optional. Default is false. If true, then a "dojo.preventCache" parameter is sent in the request with a value that changes with each request (timestamp). Useful only with GET-type requests.
sync: Optional. false is default. Indicates whether the request should be a synchronous (blocking) request.(为true则会等这个request处理完才会继续执行)
timeout: Optional. Milliseconds to wait for the response. If this time passes, the then error callbacks are called.
dojo.xhrPost
All Dojo XHR methods are bi-directional. The only difference is the method. Using dojo.xhrPost
, we use the POST method, embedding the data in the request (as opposed to the query string as with dojo.xhrGet
).
Submit the form
<form id=”loginForm”>
Name:<input type=”text” id=”firstName”/>
</form>
add in some JavaScript to submit the form by using dojo.connect
to listen to the native onSubmit
event and then post the contents of the form to an alternate URL:
var formSubmit=function(e){
e.preventDefaut(); //prevent form submit
dojo.xhrPost({
url: “ajaxServlet”,
form : “mainForm”,
handleAs : “text”,
handle : function(data, args){
…………
}
});
};
dojo.addOnLoad(function({
var theForm = dojo.byId(“loginForm”);
dojo.connect(theForm, “onclick”, formSubmit);
}));
Getting text back from the server is nice, but the really great stuff comes when you start passing JavaScript objects around. Using a different handleAs
:
“json”, we can alter how Dojo handles the response data.
如何在server端取得数据
content: {a: 11, b: 22}
String p1 = request.getParameter("a");
dojo.io.iframe
一般是用来上传文件。
<script>
function sendForm(){
url: "uploadservlet", //form's action, 如果url 或action 设定任意一个即可
method: "post", //form's method
form: "myForm", //form's id
load: function(response, ioArgs){ //succeed }
}
</script>
<form id="myForm" enctype="multipart/form-data" action="uploadServlet">
Name: <input type="text" name="name"/>
File: <input type="file" name="theFile"/>
<button onclick="sendForm();">Submit</button>
</form>
dojo.io.iframe实际上和dojo.xhr使用是相同的,不同的只是iframe可以用来上传文件