dojo/request 是创建从客户端到服务器端请求的一个新的API(1.8引入). 这个教程将介绍dojo/request API: 如何从服务器获请求一个文本文件, 当请求发现问题时如何处理。使用更高级的通知API,向服务器提交信息, 以及使用注册功能实现相同的代码请求不同处的数据。
dojo/request 是创建从客户端到服务器端请求的一个新的API(1.8引入). 这个教程将介绍dojo/request API: 如何从服务器获请求一个文本文件, 当请求发现问题时如何处理。使用更高级的通知API,向服务器提交信息, 以及使用注册功能实现相同的代码请求不同处的数据。
require(["dojo/request"],function(request){ request("helloworld.txt").then( function(text){ console.log("The file's content is: " + text); },function(error){ console.log("An error occurred: " + error); } ); });
require(["dojo/request"],function(request){ request.post("post-content.PHP",{ data: { color: "blue",answer: 42 },headers: { "X-Something": "A value" } }).then(function(text){ console.log("The server returned: ",text); }); });
require(["dojo/dom","dojo/on","dojo/request","dojo/domReady!"],function(dom,on,request){ // Results will be displayed in resultDiv var resultDiv = dom.byId("resultDiv"); // Attach the onclick event handler to the textButton on(dom.byId("textButton"),"click",function(evt){ // Request the text file request.get("../resources/text/psalm_of_life.txt").then( function(response){ // Display the text file content resultDiv.innerHTML = "<pre>"+response+"</pre>"; },function(error){ // Display the error returned resultDiv.innerHTML = "<div class=\"error\">"+error+"<div>"; } ); }); } );
require(["dojo/dom","dojo/dom-form"],domForm){ var form = dom.byId('formNode'); // Attach the onsubmit event handler of the form on(form,"submit",function(evt){ // prevent the page from navigating after submit evt.stopPropagation(); evt.preventDefault(); // Post the data to the server request.post("../resources/PHP/login-demo.PHP",{ // Send the username and password data: domForm.toObject("formNode"),// Wait 2 seconds for a response timeout: 2000 }).then(function(response){ dom.byId('svrMessage').innerHTML = response; }); }); } );
require(["dojo/dom",domForm){ // Results will be displayed in resultDiv var form = dom.byId('formNode'); // Attach the onsubmit event handler of the form on(form,function(evt){ // prevent the page from navigating after submit evt.stopPropagation(); evt.preventDefault(); // Post the data to the server var promise = request.post("../resources/PHP/login-demo.PHP",// Wait 2 seconds for a response timeout: 2000 }); // Use promise.response.then,NOT promise.then promise.response.then(function(response){ // get the message from the data property var message = response.data; // Access the 'Auth-Token' header var token = response.getHeader('Auth-Token'); dom.byId('svrMessage').innerHTML = message; dom.byId('svrToken').innerHTML = token; }); }); } );
{ "title":"JSON Sample Data","items":[{ "name":"text","value":"text data" },{ "name":"integer","value":100 },{ "name":"float","value":5.65 },{ "name":"boolean","value":false }] }
require(["dojo/dom","dojo/json","dojo/_base/array",JSON,arrayUtil){ // Results will be displayed in resultDiv var resultDiv = dom.byId("resultDiv"); // Request the JSON data from the server request.get("../resources/data/sample.json.PHP",{ // Parse data from JSON to a JavaScript object handleAs: "json" }).then(function(data){ // Display the data sent from the server var html = "<h2>JSON Data</h2>" + "<p>JSON encoded data:</p>" + "<p><code>" + JSON.stringify(data) + "</code></p>"+ "<h3>Accessing the JSON data</h3>" + "<p><strong>title</strong> " + data.title + "</p>" + "<p><strong>items</strong> An array of items." + "Each item has a name and a value. The type of " + "the value is shown in parentheses.</p><dl>"; arrayUtil.forEach(data.items,function(item,i){ html += "<dt>" + item.name + "</dt><dd>" + item.value + " (" + (typeof item.value) + ")</dd>"; }); html += "</dl>"; resultDiv.innerHTML = html; },function(error){ // Display the error returned resultDiv.innerHTML = error; }); } );
require(["dojo/dom","dojo/request/script","dojo/domReady!" ],script,JSON){ // Results will be displayed in resultDiv var resultDiv = dom.byId("resultDiv"); // Attach the onclick event handler to the makeRequest button on(dom.byId('makeRequest'),function(evt){ // When the makeRequest button is clicked,send the current // date and time to the server in a JSONP request var d = new Date(),dateNow = d.toString(); script.get("../resources/PHP/jsonp-demo.PHP",{ // Tell the server that the callback name to // use is in the "callback" query parameter jsonp: "callback",// Send the date and time query: { clienttime: dateNow } }).then(function(data){ // Display the result resultDiv.innerHTML = JSON.stringify(data); }); }); });
require(["dojo/dom","dojo/dom-construct",domConstruct,arrayUtil){ var pullsNode = dom.byId("pullrequests"); // Attach the onclick event handler to tweetButton on(dom.byId("pullrequestsButton"),function(evt){ // Request the open pull requests from Dojo's GitHub repo script.get("https://api.github.com/repos/dojo/dojo/pulls",{ // Use the "callback" query parameter to tell // GitHub's services the name of the function // to wrap the data in jsonp: "callback" }).then(function(response){ // Empty the tweets node domConstruct.empty(pullsNode); // Create a document fragment to keep from // doing live DOM manipulation var fragment = document.createDocumentFragment(); // Loop through each pull request and create a list item // for it arrayUtil.forEach(response.data,function(pull){ var li = domConstruct.create("li",{},fragment); var link = domConstruct.create("a",{href: pull.url,innerHTML: pull.title},li); }); // Append the document fragment to the list domConstruct.place(fragment,pullsNode); }); }); });查看Demo @H_403_4@
require(["dojo/dom","dojo/request/notify","dojo/query",notify,domConstruct){ // Listen for events from request providers notify("start",function(){ domConstruct.place("<p>Start</p>","divStatus"); }); notify("send",function(data,cancel){ domConstruct.place("<p>Sent request</p>","divStatus"); }); notify("load",function(data){ domConstruct.place("<p>Load (response received)</p>","divStatus"); }); notify("error",function(error){ domConstruct.place("<p class=\"error\">Error</p>","divStatus"); }); notify("done",function(data){ domConstruct.place("<p>Done (response processed)</p>","divStatus"); if(data instanceof Error){ domConstruct.place("<p class=\"error\">Error</p>","divStatus"); }else{ domConstruct.place("<p class=\"success\">Success</p>","divStatus"); } }); notify("stop",function(){ domConstruct.place("<p>Stop</p>","divStatus"); domConstruct.place("<p class=\"ready\">Ready</p>","divStatus"); }); // Use event delegation to only listen for clicks that // come from nodes with a class of "action" on(dom.byId("buttonContainer"),".action:click",function(evt){ domConstruct.empty("divStatus"); request.get("../resources/PHP/notify-demo.PHP",{ query: { success: this.id === "successBtn" },handleAs: "json" }); }); } );
request.register(url,provider,first);
require(["dojo/request/registry","dojo/dom",function(request,dom,domConstuct,on){ // Registers anything that starts with "http://" // to be sent to the script provider,// requests for a local search will use xhr request.register(/^https?:\/\//i,script); // When the search button is clicked on(dom.byId("searchButton"),function(){ // First send a request to twitter for all tweets // tagged with the search string request("http://search.twitter.com/search.json",{ query: { q:"#" + dom.byId("searchText").value,result_type:"mixed",lang:"en" },jsonp: "callback" }).then(function(data){ // If the tweets node exists,destroy it if (dom.byId("tweets")){ domConstuct.destroy("tweets"); } // If at least one result was returned if (data.results.length > 0) { // Create a new tweet list domConstuct.create("ul",{id: "tweets"},"twitterDiv"); // Add each tweet as an li while (data.results.length>0){ domConstuct.create("li",{innerHTML: data.results.shift().text},"tweets"); } }else{ // No results returned domConstuct.create("p",{id:"tweets",innerHTML:"None"},"twitterDiv"); } }); // Next send a request to the local search request("../resources/PHP/search.PHP",{ query: { q: dom.byId("searchText").value },handleAs: "json" }).then( function(data){ dom.byId('localResourceDiv').innerHTML = "<p><strong>" + data.name + "</strong><br />" + "<a href=\"" + data.url + "\">" + data.url + "</a><br />"; },function(error){ // If no results are found,the local search returns a 404 dom.byId('localResourceDiv').innerHTML = "<p>None</p>"; } ); }); } );