0
$(document).ready(function(){
    $("#btnLoad").click(function(){
        $('#div1').load('test.txt', {}, fnLoad());
    });
});

function fnLoad()
{
    // How can I load the content of <div id="div1" /> into a variable here?
}

In fact, I want to work with the variable instead of div1.innerHTML.

2
  • I haven't tried it but wouldn't var.load('test.txt',{}); work? Commented Dec 29, 2012 at 10:23
  • @Beneto, No, this type of call doesn't work. Commented Dec 29, 2012 at 10:54

2 Answers 2

2

Use $.get for xhr request, like so:

$(document).ready(function(){
    $("#btnLoad").click(function(){
        $.get('test.txt', fnLoad);
    });
});

function fnLoad(data)
{
    // Contents of test.txt should be in data argument here
}
Sign up to request clarification or add additional context in comments.

2 Comments

Could you explain more, please?
jQuery's load method loads data (usually it is an HTML string) from a web server via AJAX request and then places it into the given matched element. If you don't need to place contents of test.txt inside #div1 element and just put it in some variable, you should better use $.get method of jquery. When the data is loaded, the fnLoad function will be called and it's first argument will be what you need. If you still need the contents of test.txt placed inside #div1 - you should use the sample provided by @JamWaffles above
0
$(document).ready(function(){
    $("#btnLoad").click(function(){
        $('#div1').load('test.txt', {}, fnLoad));
    });
});

function fnLoad(result)
{
    // The variable `result` contains the response of the AJAX call.
}

This much like passing result into an anonymous function in the .load() call itself, but you've split the function out into it's own, named one. You need to pass a reference to fnLoad(). result will contain the response data. The function prototype for .load() accepts 3 arguments:

response, status, xhr

You can map these to whatever variable names you like in fnLoad().

1 Comment

This won't work, as you are passing the result of fnLoad call to function, it has to be $('#div1').load('test.txt', {}, fnLoad)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.