- Sencha Touch 教程
- Sencha Touch - 首页
- Sencha Touch - 概述
- Sencha Touch - 环境
- Sencha Touch - 命名规范
- Sencha Touch - 架构
- Sencha Touch - MVC 解释
- Sencha Touch - 第一个应用
- Sencha Touch - 构建应用程序
- Sencha Touch - 迁移步骤
- Sencha Touch - 核心概念
- Sencha Touch - 数据
- Sencha Touch - 主题
- Sencha Touch - 设备配置文件
- Sencha Touch - 依赖项
- 环境检测
- Sencha Touch - 事件
- Sencha Touch - 布局
- Sencha Touch - 历史与支持
- Sencha Touch - 上传与下载
- Sencha Touch - 视图组件
- Sencha Touch - 打包
- Sencha Touch - 最佳实践
- Sencha Touch 有用资源
- Sencha Touch - 快速指南
- Sencha Touch - 有用资源
- Sencha Touch - 讨论
Sencha Touch - Ajax
Ajax 是异步 JavaScript 和 XML。Ajax 提供了一种在不刷新整个页面的情况下获取和加载数据的功能。
Sencha Touch 提供了使用 Ajax 加载和存储数据的功能。在 Ajax 中,我们可以从同一域名获取和存储数据。它不允许我们在不同域名之间交换数据。
例如,如果您正在使用域名 www.myApp.com,则可以在同一域名的不同页面之间交换数据,例如 www.myApp.com?page=1 或 www.myApp.com/#Page.html。但是,如果您位于 www.myApp.com 域名,并且想要与其他域名(例如 www.myNewApp.com)交换数据,则不允许这样做。
尽管 Ajax 有此限制,但 Sencha Touch 允许您灵活地在不同域名之间交换数据,我们将在后续章节中学习。
简单的 Ajax 请求
Ext.Ajax.request({
url: 'myUrl', Method: 'GET', timeout: 5000, params: {
username: 'Ed', id: '1234'
},
headers: {
"Content-Type": "application/json"
},
success: function(response) {
console.log("The request was successfull");
},
failure: function(response) {
console.log("Request is failed");
},
callback: function(options, success, response) {
console.log(response.responseText);
}
});
Ext.Ajax.request 是发出 Ajax 请求的方法。
Ajax 调用中传递了不同的参数。第一个参数是发出 Ajax 请求的域的 URL。
第二个参数是 方法,它决定了发出 Ajax 请求的目的,例如 GET、POST、PUT、DELETE。Get 仅用于获取数据。POST 用于创建新数据并保存它。PUT 用于更新或替换服务器上的现有数据。DELETE 用于删除某些记录。
下一个参数是 params,我们以 JSON 格式发送数据,这有助于获取和存储数据。
Header 参数显示服务器为请求发送的数据类型。在上面的示例中,返回的数据将是 json。
回调是最有用的方法,它使整个 Ajax 概念异步。发送请求后,服务器将处理请求并发送响应。一旦我们收到响应,回调函数将被调用。基于此,我们可以获得成功、失败或正常的回调。
因此,如果响应成功,则会调用 success 回调,如果响应失败,则会调用 failure 回调。如果我们没有定义任何 success 或 failure,则会调用正常的回调。在回调中,我们可以在获得特定响应后编写我们想要处理的代码。
有时请求需要很长时间才能响应,并且会发生超时。超时的默认时间为 30 秒。我们可以通过 ajax 请求中传递的 timeout 参数来自定义它。如上例所示,超时时间为 5000 毫秒。一旦发生超时,就会调用 failure 函数。
也可以通过调用来中止请求。
var myReq = Ext.Ajax.request({
url: 'myUrl', failure: function(response) {
console.log(response.aborted);
}
});
Ext.Ajax.abort(myReq);
一旦请求被中止,就会调用 failure 回调。如果 response.aborted 返回 true,则表示由于请求中止而导致失败。
跨域请求
Ajax 请求只能在同一域名中进行,但是 Sencha 提供了进行跨域请求的功能。
现代浏览器提供了一个新的功能 CORS(跨源资源共享),以便可以在没有浏览器安全限制的情况下进行跨域请求。如果您的 Web 服务器启用了 CORS,那么在 Sencha Touch 中,您需要在 Ajax 请求中提供参数,然后就可以进行跨域请求。
Ext.Ajax.request({
url: 'https://www.myNewDomain.com/newPage.html', withCredentials: true, useDefaultXhrHeader: false
});