Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load the content of a file into variable using jquery load method?

Tags:

jquery

ajax

How do I load the content of a file into a variable instead of the DOM using jQuery .load() method?

For example,

$("#logList").load("logFile", function(response){ }); 

Instead of loading the file into the #logList element of the DOM, I would like it to load into a variable.

like image 861
Yetimwork Beyene Avatar asked Jul 20 '12 16:07

Yetimwork Beyene


People also ask

What is the load () method used for in jQuery?

The jQuery load() method is a simple, but powerful AJAX method. The load() method loads data from a server and puts the returned data into the selected element.

How can we call a method on page load using jQuery?

Method 1: Using the on() method with the load event: The on() method in jQuery is used to attach an event handler for any event to the selected elements. The window object is first selected using a selector and the on() method is used on this element.

Does jQuery load execute JavaScript?

load() call doesn't execute JavaScript in loaded HTML file.


2 Answers

load() is just a shortcut for $.get that atuomagically inserts the content into a DOM element, so do:

$.get("logFile", function(response) {      var logfile = response; }); 
like image 103
adeneo Avatar answered Sep 22 '22 12:09

adeneo


You can use $.get() to initiate a GET request. In the success callback, you can set the result to your variable:

var stuff; $.get('logFile', function (response) {     stuff = response; }); 

Please note that this is an asynchronous operation. The callback function will run when the operation is completed, so commands after $.get(...) will be executed beforehand.

That's why the following will log undefined:

var stuff; $.get('logFile', function (var) {     stuff = var; }); console.log(stuff); //undefined 
like image 29
kapa Avatar answered Sep 22 '22 12:09

kapa