jQuery in Action
248
CHAPTER 8
Talk to the server with Ajax
var selectElement = this;
$.each(optionsDataArray,function(index,optionData){
var option = new Option(optionData.caption,
optionData.value);
if ($.browser.msie) {
selectElement.add(option);
}
else {
selectElement.add(option,null);
}
});
}
});
}
})(jQuery);
Between
$.get()
and
$.getJSON()
, jQuery gives us some powerful tools when it
comes to making
GET
requests, but man does not live by
GET
s alone!
8.3.3 Making POST requests
"Sometimes you feel like a nut, sometimes you don't." What's true of choosing
between an Almond Joy or a Mounds candy bar is also true of making requests to
the server. Sometimes we want to make a
between an Almond Joy or a Mounds candy bar is also true of making requests to
the server. Sometimes we want to make a
GET
, but at other times we want (or
need) to make a
POST
request.
There are any number of reasons why we might choose a
POST
over a
GET
.
First, the intention of the
HTTP
protocol is that
POST
will be used for any non-
idempotent requests. Therefore, if our request has the potential to cause a
change in the server-side state, it should be a
change in the server-side state, it should be a
POST
(at least according to
HTTP
purists). Accepted practices and conventions aside, a
POST
operation must some-
times be used when the data to be passed to the server exceeds the small amount
that can be passed by
that can be passed by
URL
in a query string; that limit is a browser-dependent
value. And sometimes, the server-side resource we contact may only support
POST
operations, or it might even perform different functions depending upon
whether our request uses the
GET
or
POST
method.
For those occasions when a
POST
is desired or mandated, jQuery offers the
$.post()
utility function, which operates in the exact same fashion as
$.get()
except for the
HTTP
method used. Its syntax is as follows: