JQuery gets attached to Ajax success

Why do we call bind on AJAX success calls?

Take a look at this code:

 $.ajax({ url: myurl, dataType: 'json', success: function(data){ this.setState({data: data}); }.bind(this) }); 

If we do not call bind , does this have any meaning or is there an advantage to using bind here?

+8
javascript jquery ajax bind
source share
4 answers

You need to call bind() to make the callback context ( this ) be correct. Otherwise, it is called in the global context by default (apparently, jQuery calls it with the context of the jqXHR object). bind() sets the context of your function no matter what this should be.

+8
source share

@shubham, this is JavaScript to use the current this in your callback function, as you mentioned in:

 success: function(data){ this.setState({data: data}); } 

The first argument of the bind() function will act as follows when calling the function, you must go through the apply() and call() functions, as this will be useful for you.

+1
source share

I assume your code is from React . Since I recently encountered a similar problem related to React .

Let's get back to your question. I think bind plays a conversion function. The code is as follows:

 componentDidMount: function() { var _this = this; $.ajax({ url: this.props.url, dataType: 'json', cache: false, success: function(data) { _this.setState({data: data}); } }); }, 

equally:

 componentDidMount: function() { $.ajax({ url: this.props.url, dataType: 'json', cache: false, success: function(data) { this.setState({data: data}); }.bind(this) }); }, 

As for, I think you can understand that this is a function to bind and why use bind to achieve it.

+1
source share

I agree that Scimonster.bind () sets the context of your function as it should be, or your function will throw this error: Uncaught TypeError: this.setState is not a function

0
source share

All Articles