$ (this) does not work in function

The following code loads the html content from a file (I used this stream )

<script> $.fn.loadWithoutCache = function (){ $.ajax({ url: arguments[0], cache: false, dataType: "html", success: function(data) { $(this).html(data); // This is not working //$('#result').html(data); //THIS WORKS!!! alert(data); // This alerts the contents of page.html } }); } $('#result').loadWithoutCache('page.html'); </script> 

Please let me know what is the problem? Hope this is something stupid :)

Edit: CORRECT CODE

 <script> $(document).ready(function() { $.fn.loadWithoutCache = function (){ var $el = $(this); $.ajax({ url: arguments[0], cache: false, dataType: "html", context: this, success: function(data) { $el.html(data); } }); } $('#result').loadWithoutCache('page.html'); }); </scipt> 

Thanks John and that’s it!

+4
source share
5 answers

The success callback function is launched when the response arrives, and it does not run in the scope of the loadWithoutCache method, as it has already ended.

You can use the context property in an ajax call to set the context of the callback functions:

 $.fn.loadWithoutCache = function (){ $.ajax({ url: arguments[0], cache: false, dataType: "html", context: this, success: function(data) { $(this).html(data); } }); } 
+3
source

The problem is that inside the success callback this does not matter what you expect from it.

However, you do have access to this (with the expected value) inside loadWithoutCache . Thus, you can achieve your goal by storing $(this) in a local variable and accessing it from the success handler (by creating a closure).

This is what you need to do:

 $.fn.loadWithoutCache = function (){ var $el = $(this); $.ajax({ url: arguments[0], cache: false, dataType: "html", success: function(data) { $el.html(data); alert(data); } }); } 
+6
source

Incorrect definition of this . You need to store this in a variable outside the ajax success function and reference it from this variable

 <script> $.fn.loadWithoutCache = function (){ var self = this; $.ajax({ url: arguments[0], cache: false, dataType: "html", success: function(data) { self.html(data); // This is not working //$('#result').html(data); //THIS WORKS!!! alert(data); // This alerts the contents of page.html } }); } $('#result').loadWithoutCache('page.html'); 

+2
source

In an AJAX callback, this bound to another object. If you want to reuse the purpose of your plugin, save (capture) it in a local variable and use it.

 $.fn.loadWithoutCache = function (){ var $target = $(this); $.ajax({ url: arguments[0], cache: false, dataType: "html", success: function(data) { $target.html(data); // note change } }); } 
+2
source

JQuery is contextual. http://remysharp.com/2007/04/12/jquerys-this-demystified/

console.log($(this)) at different points to see what this refers to.

+1
source

Source: https://habr.com/ru/post/920543/


All Articles