Yetimwork Beyene
Yetimwork Beyene

Reputation: 2337

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

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.

Upvotes: 31

Views: 35772

Answers (2)

adeneo
adeneo

Reputation: 318202

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;
});

Upvotes: 39

kapa
kapa

Reputation: 78681

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

Upvotes: 23

Related Questions