简体   繁体   中英

Fetch an html element from external page with javascript

I'm trying to create a function in javascript the will create a video html element, and get the source by retrieving a source element from another web page

I've seen other questions with answers using jquery or some ajax stuff, but nobody actually explains themselves, so all I can do is copy and paste whatever they say into my page and get an error saying "$" is undefined (I'm rather new to javascript if you couldn't tell. Haven't used any ajax or jquery yet).

function loadSource(url){
    var vid = document.getElementById("vid");
    var src = <get source element with id "mp4Source" from the specified url>
    vid.appendChild(src);
}

The reason why you're getting $ as undefined is because you have not added the JQuery Library.

There is a good question explaining how to get setup here

Above your JavaScript, you need to include the JQuery Library.

Example of how to include the JQuery Library

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

As for loading the external video element, you need to make an AJAX request to the URL containing the element. AJAX is a way to perform Asynchronous HTTP requests, eg requests that are made to a URL without refreshing the web page.

Example of how AJAX can be used to pull HTML from an external URL

function loadSource(url){
    $.ajax({
        url: "<URL containing the HTML>",
    })
    .done(function(html) {
        $("#vid").append(html); // append the html to the element with the ID 'vid'
    });
}

More information on AJAX can be found at http://api.jquery.com/jquery.ajax/

You should also look into the basics of JQuery, such as looking here . An example of how this could be used in your code is by replacing document.getElementById("vid") with $("#vid") .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM