문제

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