It works in many ways.
For example, Google offers two basic advertising models. Google Adwords and Google Adsense. Both incorporate
keyword indexing scripts but are otherwise vastly different programs. For a more complete overview of Google advertising options, go here and read the FAQs and Information pages:
http://www.google.com/intl/en/ads/Then there is BlogAds - a company that revolutionized Internet advertising with their publisher/blog/network model. With BlogAds, you can choose to advertise ala carte on targeted blogs or you can buy a package, where you choose a particular audience niche. BlogAds has become so successful because it is the easiest, most direct way an individual can make money from their own content.
Of course, there are good old placement ads but the majority of them are handled by Internet advertising networks, that also target specific audiences and - as is common with such platforms - the targeting is done with the aid of software and is far from perfect.
There is geo-targeting. This is where magical scripts and and pixies determine a user's geographic location and as a result, feed them advertising specific to common marketing statistics of that area...
I could go on but I keep realizing that I'm giving away my precious goodies and I should just write a damned book.
/rant over
EDIT: I am my own crappy editor