So I’m working on making a dynamic drop down select form and I need for each menu to propagate possible choices from a prebuilt chunk of html (located at, say, http://example.com/menu/choices) is there an easy way to use javascript to fetch the html of a remote page and then plug that in to the page? I know I can use .write() to insert the code, I just don’t know how to fetch it.
Thanks!
Actually, you can’t use
writeto insert the code, not once the initial page rendering is complete.Loading Code
My first read of your question was that you wanted to load code — e.g., JavaScript. Here’s how you do that, but see below.
The easiest way to do this is if your code exists at its source location in a JavaScript file all ready for inclusion in a file in the normal way. In that case, all you need to do is create a
scriptelement and add it to the document:Note that last line, removing the
scriptnode immediately after inserting it in the document. Inserting the node is all you need to do, that immediately triggers the process by which the JavaScript file is fetched and interpreted. You can remove the script element immediately (or not, it’s up to you).In the above, I’ve added the element to
document.bodybecause it’s convenient and it doesn’t matter where you add it. However, most scripts you see doing this will usually add it to theheadinstead. That’s fine too. More in this article, although it’s focussed on the Prototype library.Speaking of libraries, all of the above notwithstanding, if you use a JavaScript library like jQuery, Closure, Prototype, YUI, or any of several others, it will probably make this (even) easier for you.
Update: Did you add the
jQuerytag later? I didn’t see it originally. With jQuery, if you’re loading the script from the same origin as the document, you can use thegetScriptfunction:However,
getScriptis not the same as the technique above.getScriptwill be hampered by the Same Origin Policy, whereas adding ascripttag is not.Loading Markup
If you want to load HTML markup and apply it to part of a page, that’s easily done with
jQuery.load:That will replace the contents of the element with the id “someid” with the HTML returned from the given URL. Here’s a live example that loads
options into aselectand another that loads text (a paragraph) into a div. This is easier with a library (like jQuery) because there are some issues around certain elements that libraries usually handle for you.