原文地址:http://docs-origin.sencha.com/touch/2.2.0/#!/guide/ajax
Using AJAX with Sencha Touch
在st中使用AJAX
Sencha Touch provides a variety of convenient ways to get data into and out of your application. All of the data-bound Components such as Lists, Nested Lists, and DataViews use Stores, which are easily configured to fetch and save data to a large variety of sources. We will look at managing data with stores later on, but first let us start with how to generate simple AJAX requests.
st提供了很多种向应用导入导出数据的方式。所有的数据绑定组件,例如Lists、Nested List及DataViews都使用了很容易配置的数据存储来从大量的数据源存取数据。我们稍后会看如何管理数据存储的数据,首先我们看下如何生成一个简单的ajax请求。
Simple Requests with Ext.Ajax
用Ext.Ajax发送简单的请求
Because of browser security restrictions, AJAX requests are usually made to urls on the same domain as your application. For example, if your application is found at http://myapp.com, you can send AJAX requests to urls such as http://myapp.com/login.php and http://myapp.com/products/1.json, but not to other domains such as http://google.com. However, Sencha Touch provides some alternatives to get around this limitation, as shown in the final part of this guide (Cross-Domain Requests and JSON-P).
由于浏览器安全策略的限制,ajax请求通常与你的应用使用相同的域。例如,如果你的应用建立在http://myapp.com, 你可以向这些url发送请求,http://myapp.com/login.php 、http://myapp.com/products/1.json,但是不能向其它域如http://google.com发送请求。然而,st提供了几种绕开该限制的方法,如该向导的最后一部分所述(Cross-Domain Request 和JSON-P).
The following code shows an AJAX request to load data from an url on the same domain:
下面的代码展示了向同一个域上的url请求数据:
Ext.Ajax.request({
url: 'myUrl',
callback: function(options, success, response) {
console.log(response.responseText);
}
});
Assuming that your app is on http://myapp.com, the previous code sends a GET request to http://myapp.com/myUrl. Since AJAX calls are asynchronous, once the response comes back, the callback function is called with the response. In this example the callback function logs the contents of the response to the console when the request has finished.
假设你的app在http://myapp.com上,上面的代码向http://myapp.com/myUrl发送了一个get请求。尽管AJAX调用是异步的,一旦响应返回,callback函数就会被调用。在这个例子中,当请求结束时,callback函数会将响应的内容打印出来。
AJAX Options
AJAX配置项
Ext.Ajax takes a wide variety of options, including setting the method (GET, POST, PUT, or DELETE), sending headers, and setting params to be sent in the url. The following code sets the method such that a POST request is sent instead of a GET:
Ext.Ajax有大量的配置项,包括设置请求方法(GET、POST、PUT 或者DELETE),请求头,url中要发送的参数。下面的代码设置了请求的方法为POST而不是GET:
Ext.Ajax.request({
url: 'myUrl',
method: 'POST',
callback: function(options, success, response) {
console.log(response.responseText);
}
});
Sending parameters done as shown in the following example:
发送参数如下面的代码所示:
Ext.Ajax.request({
url: 'myUrl',
params: {
username: 'Ed',
password: 'not a good place to put a password'
},
callback: function(options, success, response) {
console.log(response.responseText);
}
});
When setting parameters like in this example, the request is automatically sent as a POST with the params object sent as form data. The previous request above is like submitting a form with username and password fields.
当像上面的例子所示设置参数时,请求会自动将参数作为表单数据发送一个post请求。上面的请求提交了一个有username和password字段的表单。
If we wanted to send this as a GET request instead, we would have to specify the method again, in which case our params are automatically escaped and appended to the url:
如果我们想将上述请求改为get请求,我们需要再次指定method方法,这时我们的参数会自动过滤并追加到url后:
Ext.Ajax.request({
url: 'myUrl',
method: 'GET',
params: {
username: 'Ed',
password: 'bad place for a password'
},
callback: function(options, success, response) {
console.log(response.responseText);
}
});
The previous code sample generates the following request:
上面的代码生成了如下的请求:
http://mywebsite.com/myUrl?_dc=1329443875411&username=Ed&password=bad%20place%20for%20a%20password
You may have noticed that our request created an url that contained "_dc=1329443875411". When you make a GET request like this, many web servers cache the response and send you back the same response every time you make the request. Although this speeds the web up, it is not always what you want. In fact in applications this is rarely what you want, so we "bust" the cache by adding a timestamp to every request. This tells the web server to treat it like a fresh, uncached request.
你可能会发现我们的请求创建了一个包含“_dc=1329443875411”参数的url。当你像上面这样创建一个get请求时,很多web服务器会缓存该响应并在每次接到该请求时都返回你相同的响应。尽管这提供了web访问速度,但是它并不总是你想要的。事实上,在应用程序中,这几乎不是你想要的,因此我们通过为每一个请求添加时间戳来禁用缓存。这告诉web服务器它是一个新的、不缓存的请求。
If you want to turn this behavior off, we ccould set disableCaching to false, as shown in the following code sample:
如果你想关闭该功能,可以设置disableCaching 为false,如下面的代码所示:
Ext.Ajax.request({
url: 'myUrl',
method: 'GET',
disableCaching: false,
params: {
username: 'Ed',
password: 'bad place for a password'
},
callback: function(options, success, response) {
console.log(response.responseText);
}
});
Since the request no longer contains the cache busting string, it looks like the following string:
因为请求不再包含缓存字符串,请求url如下所示:
http://mywebsite.com/myUrl?username=Ed&password=bad%20place%20for%20a%20password
Sending Headers
发送头信息
Another option related to customizing the request is the headers option. This enables you to send any custom headers to your server, which is often useful when the web server returns different content based on these headers. For example, if your web server returns JSON, XML, or CSV based on the header it is passed, we can request JSON like in the following example:
请求的另一个可配置项时头信息。这让你能够将任何客户头信息发送给服务器,这在服务器依据不同的头信息返回不同的内容时很有用。例如,如果你的web服务器依据头信息返回json、xml或者csv时,我们可以像下面这样请求json:
Ext.Ajax.request({
url: 'myUrl',
headers: {
"Content-Type": "application/json"
},
callback: function(options, success, response) {
console.log(response.responseText);
}
});
If you create a request like this and inspect it in Firebug/web inspector, you will see that the Content-Type header has been set to application/json. Your web server can pick up on this and send you the right response. You can pass any number of headers you like into the headers option.
如果你像上面那样创建了一个请求,并在firebug、web监视器中查看,你可以看到Content-Type头被设置成了application/json。你的web服务器能够获得该信息并给你正确的响应。你可以在headers配置中传递任意数量的头信息。
Callback Options
回调功能
Not every AJAX request succeeds: sometimes the server is down, or your internet connection drops, or something else bad happens. Ext.Ajax allows you to specify separate callbacks for each of these cases:
不是每一个的ajax请求都会成功:有时,服务器挂了或者网络连接断了亦或者发生了其它一些事。Ext.Ajax允许你为不同的情况指定回调函数:
Ext.Ajax.request({
url: 'myUrl',
success: function(response) {
console.log("Spiffing, everything worked");
},
failure: function(response) {
console.log("Curses, something terrible happened");
}
});
These do exactly what you would expect them to do, and hopefully most of the time it is your success callback that gets called. It is pretty common to provide a success callback that updates the UI or does whatever else is needed by the application flow, and a failure handler that either resends the request or alerts the user that something went wrong.
这会根据你的意愿去做正确的处理,并且通常情况下会调用success回调函数。提供一个success回调函数来更新ui或者做一些其它必要的事情、一个failure回调函数处理重新请求或者给用户弹出一个错误提示窗口是相当不错的做法。
You can provide success/failure and callback at the same time, so for this request the success function is called first (if everything was ok), followed by the maincallback function. In the case of failure, the failure function is called first, followed by callback:
你也可以同时提供success/failure和callback,这种情况下,如果一切正常,该请求会首先调用success方法然后调用callback,在失败的情况下,会先调用failure方法再调用callback方法:
Ext.Ajax.request({
url: 'myUrl',
success: function(response) {
console.log("Spiffing, everything worked");
},
failure: function(response) {
console.log("Curses, something terrible happened");
},
callback: function(options, success, response) {
console.log("It is what it is");
}
});
Timeouts and Aborting Requests
超时和废弃请求
Another way requests can fail is when the server took too long to respond and the request timed out. In this case your failure function is called, and the request object it is passed has the timedout variable set to true:
请求失败的另一种情况是服务器需要很长时间响应导致请求超时。在这种情况下,failure方法被调用,传递的请求对象的timedout参数被设为true:
Ext.Ajax.request({
url: 'myUrl',
failure: function(response) {
console.log(response.timedout); // logs true
}
});
By default the timeout threshold is 30 seconds, but you can specify it for every request by setting the timeout value in millisecond. In the following case the request will give up after 5 seconds:
默认情况系下,超时阈值为30s,但是你可以设置timeout参数为多少毫秒来指定每一个请求的超时阈值。在下面的例子中,请求会在5s后放弃:
Ext.Ajax.request({
url: 'myUrl',
timeout: 5000,
failure: function(response) {
console.log(response.timedout); // logs true
}
});
It is also possible to abort requests that are currently outstanding. In order to do this, you need to save a reference to the request object that Ext.Ajax.request returns, as shown in the following code sample:
废弃当前尚未完成的请求也是可能的。为了达到这个目的,你需要保存对请求对象的引用,即Ext.Ajax.request返回的对象,如下所示:
var myRequest = Ext.Ajax.request({
url: 'myUrl',
failure: function(response) {
console.log(response.aborted); // logs true
}
});
Ext.Ajax.abort(myRequest);
This time the failure callback is called and its response.aborted property is set. You can use all of the error handling above in your apps:
这一次,failure方法会被调用,并且response.aborted参数会被设置。你可以在你的app中使用下面所有的错误处理:
Ext.Ajax.request({
url: 'myUrl',
failure: function(response) {
if (response.timedout) {
Ext.Msg.alert('Timeout', "The server timed out :(");
} else if (response.aborted) {
Ext.Msg.alert('Aborted', "Looks like you aborted the request");
} else {
Ext.Msg.alert('Bad', "Something went wrong with your request");
}
}
});
Cross-Domain Requests
跨域请求
A relatively new capability of modern browsers is called CORS, which stands for Cross-Origin Resource Sharing. This allows you to send requests to other domains, without the usual security restrictions enforced by the browser. Sencha Touch provides support for CORS, although you will probably need to configure your web server in order to enable it. If you are not familiar with the required actions for setting up your web server for CORS, a quick web search should give you plenty of answers.
现代浏览器的一个相对比较新的功能叫CORS,代表Cross-Origin Resource Sharing(跨域资源共享)。这允许你撇开浏览器的安全策略要求向其他的域发起请求。st对cors提供了支持,但是你需要配置你的服务器以允许它。如果你对配置web服务器允许cors不熟,一个快速的检索将给你很多答案。
Assuming your server is set up, sending a CORS request is easy:
假设你的服务器已经配置好了,发送一个cors请求是很简单的:
Ext.Ajax.request({
url: 'http://www.somedomain.com/some/awesome/url.php',
withCredentials: true,
useDefaultXhrHeader: false
});
Form Uploads
表单上传
The final topic covered in this guide is uploading forms, a functionality that is illustrated in the following sample code:
本向导包含的最后一个话题 是表单上传,如下代码所示的功能:
Ext.Ajax.request({
url: 'myUrl',
form: 'myFormId',
callback: function(options, success, response) {
if (success) {
Ext.Msg.alert('Success', 'We got your form submission');
} else {
Ext.Msg.alert('Fail', 'Hmm, that did not work');
}
}
});
This finds a <form> tag on the page with id="myFormId", retrieves its data and puts it into the request params object, as shown at the start of this guide. Then it submits it to the specified url and calls your callbacks like normal.
这会寻找页面上id = “myFormId”的<form>标签,检索表单里的数据并将其放入请求的params参数,如本篇开始里所提到的样。然后会跟正常情况下样提交到指定的url并执行callback回调函数。
昨晚的今天来补上!