Вопрос

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.

Это было полезно?

Решение 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

Другие советы

You can do it with several AJAX functions, like:

$.ajax('file.php').done(function(e) {
    $('a#myLink').attr('href', e);
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top