Domanda

I want to load an url from an external file, for an attribute "href". My code :

var url = $("file.php div#data").html()

$("a#myLink").attr('href',url);

This doesn't work. Why ? Should I use ".load" ? ".ajax" ? Thanks.

È stato utile?

Soluzione 2

You need to use AJAX to load the file. However, it might be easier to use PHP to output the JS for the link, seeing as JavaScript without AJAX can't access files (due to the JS engine's security settings).

var txtFile = new XMLHttpRequest(); txtFile.open("GET", "http://my.remote.url/myremotefile.txt", true); txtFile.onreadystatechange = function() { if (txtFile.readyState === 4) { // Makes sure the document is ready to parse. if (txtFile.status === 200) { // Makes sure it's found the file. allText = txtFile.responseText; lines = txtFile.responseText.split("\n"); // Will separate each line into an array } } } txtFile.send(null);

Answer reproduced from https://stackoverflow.com/a/5437603/2225787

Altri suggerimenti

You can do it with several AJAX functions, like:

$.ajax('file.php').done(function(e) {
    $('a#myLink').attr('href', e);
});
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top