Ember.js中的 ajax.send用法
时间: 2024-03-20 19:41:42 浏览: 16
在 Ember.js 中,`ajax.send()` 并不是官方推荐的方式来发送 AJAX 请求,而是底层的私有 API。官方推荐的方式是使用 `Ember.$.ajax()` 或 `Ember.ajax()`。
如果你非常确定要使用 `ajax.send()` 发送请求,可以按照以下方式使用:
```
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
submitForm() {
const data = {
username: 'john'
};
Ember.$.ajax({
url: '/api/users',
type: 'POST',
data: JSON.stringify(data)
}).then(function(response) {
console.log(response);
}).catch(function(error) {
console.log(error);
});
}
},
setupController(controller, model) {
this._super(controller, model);
const ajax = Ember.$.ajax({
url: '/api/users',
type: 'GET'
});
ajax.then(function(response) {
console.log(response);
});
ajax.catch(function(error) {
console.log(error);
});
ajax.send(); // 发送请求
}
});
```
在这个例子中,我们在 `setupController` 钩子函数中使用 `Ember.$.ajax()` 创建一个 AJAX 请求对象 `ajax`,然后使用 `ajax.send()` 方法发送请求。在 `submitForm` 钩子函数中,我们使用 `Ember.$.ajax()` 直接发送一个 POST 请求。
需要注意的是,使用 `ajax.send()` 发送请求时,必须先创建一个 AJAX 请求对象,然后在对象上调用 `send()` 方法。此外,在 Ember.js 中,不建议直接使用底层的私有 API,因为它可能会在未来的版本中发生变化。如果可能的话,应该尽量使用官方推荐的方式发送 AJAX 请求。