JQuery 绑定 Ajax 成功
JQuery bind on Ajax success
为什么我们在 AJAX success
调用时调用绑定?
看看这段代码:
$.ajax({
url: myurl,
dataType: 'json',
success: function(data){
this.setState({data: data});
}.bind(this)
});
如果我们不调用 bind
,那么这里使用 bind
有什么不同或有优势吗?
您需要调用 bind()
以强制您的回调上下文 (this
) 是正确的。否则,它默认在全局上下文中调用(显然,jQuery 使用 jqXHR 对象的上下文调用它)。 bind()
将函数的上下文设置为 this
应该是什么。
@shubham,这是 JavaScript 语法,可以在你的回调函数中使用当前 this,正如你在以下内容中提到的:
success: function(data){
this.setState({data: data});
}
bind()
函数的第一个参数将在调用函数时充当 this,您应该通过 apply()
和 call()
函数,因为这对您有帮助。
我想你的代码来自 React。因为最近我遇到了处理 React.
的类似问题
回到你的问题。我认为 bind
是起到变换的作用。代码如下:
componentDidMount: function() {
var _this = this;
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
_this.setState({data: data});
}
});
},
等于:
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this)
});
},
至于,我想你能理解什么是bind功能,为什么要用bind
来实现。
为什么我们在 AJAX success
调用时调用绑定?
看看这段代码:
$.ajax({
url: myurl,
dataType: 'json',
success: function(data){
this.setState({data: data});
}.bind(this)
});
如果我们不调用 bind
,那么这里使用 bind
有什么不同或有优势吗?
您需要调用 bind()
以强制您的回调上下文 (this
) 是正确的。否则,它默认在全局上下文中调用(显然,jQuery 使用 jqXHR 对象的上下文调用它)。 bind()
将函数的上下文设置为 this
应该是什么。
@shubham,这是 JavaScript 语法,可以在你的回调函数中使用当前 this,正如你在以下内容中提到的:
success: function(data){
this.setState({data: data});
}
bind()
函数的第一个参数将在调用函数时充当 this,您应该通过 apply()
和 call()
函数,因为这对您有帮助。
我想你的代码来自 React。因为最近我遇到了处理 React.
的类似问题回到你的问题。我认为 bind
是起到变换的作用。代码如下:
componentDidMount: function() {
var _this = this;
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
_this.setState({data: data});
}
});
},
等于:
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this)
});
},
至于,我想你能理解什么是bind功能,为什么要用bind
来实现。