阮一峰的IT笔记:首页 -> 分类 -> Javascript 查看所有文章:按分类 | 按月份

用XML HTTP 对象进行POST请求

The second most common type of HTTP request is a POST. Typically, POST requests are used when entering data into a Web form because they are capable of sending much more data (around 2 GB) than GET requests.

Just like a GET request, the parameters for a POST request must be encoded for use in a URL and separated with an ampersand, although the parameters aren’t attached to the URL. When sending a POST request, you pass in the parameters as an argument to the send()method:

oRequest.open(“post”, “page.php”, false); oRequest.send(“name1=value1&name2=value2”);

It also helps to have a function for formatting the parameters for a POST request:

function addPostParam(sParams, sParamName, sParamValue) { if (sParams.length > 0) { sParams += “&”; } return sParams + encodeURIComponent(sParamName) + “=” + encodeURIComponent(sParamValue); }

This function is similar to the addURLParam()function, although addPostParam()deals with a string of parameters instead of a URL. The first argument is the existing list of parameters, the second argument is the parameter name, and the third is the parameter value. The function checks whether the length of the parameters string is longer than 0. If so, then it adds an ampersand to separate the new parameter. Otherwise, it returns the parameter string with the new name and value added. Here’s a brief example of its use:

var sParams = “”;
sParams = addPostParam(sParams, “name”, “Nicholas”);
sParams = addPostParam(sParams, “book”, “Professional JavaScript”);
oRequest.open(“post”, “page.php”, false);
oRequest.send(sParams);

Even though this looks like a valid POST request, a server-side page expecting a POST actually won’t interpret this code correctly. That’s because all POST requests sent by a browser have the “ContentType”header set to “application/x-www-form-urlencoded”. Fortunately, that can be easily corrected using the setRequestHeader()method:

var sParams = “”;
sParams = addPostParam(sParams, “name”, “Nicholas”);
sParams = addPostParam(sParams, “book”, “Professional JavaScript”);
oRequest.open(“post”, “page.php”, false);
oRequest.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);
oRequest.send(sParams);

Now this example works just like a form POSTed from a Web browser.

« 用XML HTTP 对象进行GET请求 | 首页 | 建立通用的HTTP请求对象 »

About

This page contains a single entry from the blog posted on 2007年07月29日 15:50.

The previous post in this blog was 用XML HTTP 对象进行GET请求.

The next post in this blog is 建立通用的HTTP请求对象.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33

Post a comment