First, Germany and Japan issued unconditional surrenders.
There was no way hardliners could admit anything but that they had been defeated. And with their infrastructures destroyed, rebuilding efforts allowed the countries to be remade from dictatorships into representative governments.
Also, time, money, and the will to make a dedicated change.
It's not so much the unconditional surrender thing, it's more that there weren't organized forces of resistance to the new government with external support. If the Germans had surrendered, but were surrounded by other fascist countries on all sides who were spilling across the borders with cash, guns and foreign volunteer fighters, then the occupation of Germany would have involved years of insurgency, just like Afghanistan and Iraq.
The second main difference is the absence of a strong ideological component. Nazi ideology was a flash in the pan. It appeared and was snuffed out inside of 20 years. Now all you have is trace remnants from people who don't really understand it and people who get called Nazis but are actually just racists. There was no Japanese imperial cult that took firm root in other countries, there were no Nazi states outside of Germany. There was nobody else to look to for a sense of legitimacy and kinship. When the Emperor of Japan was going along with the occupation, that was all she wrote. There weren't foreign imperial Japanese priests calling for a holy war and condemning the invaders. The Nazi allies, loosely considered Fascists, were ideologically divergent and flocked together only out of political opportunism. Even they had also been occupied with the exception of Franco's Spain. Nazism had promised the world and had instead been thoroughly discredited and crushed.
The third main difference is that all of these countries were utterly devastated and their population of able bodied young (and also old) men were severely depleted. These sorts of people would have been the lifeblood of any resistance but the most ideologically fanatical had already gone to war six years earlier huge numbers of them had died or been wounded. The people were physically and psychologically exhausted and needed to fully rely on their occupying forces for basic necessities like food and shelter.
The reconstruction you mention is also part of it, but there's a difference in scale here too. Germany and Japan were smashed to pieces and had to be put back together. Iraq and Afghanistan were comparatively less devastated, but also comparatively less prosperous to begin with.