Headspace in the carboy is nice to avoid this, but ultimately, a blow-off tube is the answer. By switching out the airlocks, you did the right thing, and ultimately, as long as you didn't let it sit exposed for a long period of time (in the realm of 20+ minutes), the likelihood of infection isn't high. Plus, the krausen (foamy stuff that sits on top of the wort while fermenting) acts as a protective layer from bacteria. By the time the krausen dies down, the bacteria will come in contact with alcohol, lessening the chances for infection (hopefully).
Simplest way to do this, take apart a 3-piece airlock, determine the diameter of the inner tube that feeds into the bucket (I don't know the diameter off the top of my head), and get about 3-4 feet of tubing that size. Plug one end of the top of that inner plastic tube of the airlock, fill a bucket, or some form of container with sanitizer, and put the loose end in the sanitizer completely submerged. Now, if anything comes out the top, it simply goes into the container, no bucket/carboy-bombs.
EDIT: Visited the LHBS today on the way home to get my next recipe. You want half-inch (either thin or thick wall, both will work) hosing, at least 3 feet, ideally 4, for your blow off tube.
By the way, this is very common. The investment of a blow off is well worth the cost. Seeing yeast shoot out of the carboy (ideally through a blow-off tube, but any way works, albeit a bit messy without) is one of the most fascinating parts of brewing.