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

建立通用的HTTP请求对象

var bXmlHttpSupport = (typeof XMLHttpRequest == “object” || window.ActiveXObject);

var Http = new Object;

定义回调函数:

function callback_function(sData) {
//interpret data here
}

定义GET方法:

Http.get = function (sURL, fnCallback) {
if (bXmlHttpSupport) {
var oRequest = new XMLHttpRequest();
oRequest.open(“get”, sURL, true);
oRequest.onreadystatechange = function () {
if (oRequest.readyState == 4) {
fnCallback(oRequest.responseText);
}
}
oRequest.send(null);
} else {
alert(“Your browser doesn’t support HTTP requests.”);
}
};

GET方法使用示例:

var sURL = “http://www.somewhere.com/page.php”;
sURL = addURLParam(sURL, “name”, “Nicholas”);
sURL = addURLParam(sURL, “book”, “Professional JavaScript”);
Http.get(sURL, function(sData) {
alert(“Server sent back: “ + sData);
});

定义POST方法:

Http.post = function (sURL, sParams, fnCallback) {
if (bXmlHttpSupport) {
var oRequest = new XMLHttpRequest();
oRequest.open(“post”, sURL, true);
oRequest.setRequestHeader(“Content-Type”,
“application/x-www-form-urlencoded”);
oRequest.onreadystatechange = function () {
if (oRequest.readyState == 4) {
fnCallback(oRequest.responseText);
}
}
oRequest.send(sParams);
} else {
alert(“Your browser doesn’t support HTTP requests.”);
}
};

使用POST方法示例:

var sURL = “http://www.somewhere.com/page.php”;
var sParams = “”;
sParams = addPostParam(sParams, “name”, “Nicholas”);
sParams = addPostParam(sParams, “book”, “Professional JavaScript”);
oHttp.post(sURL, function(sData) {
alert(“Server sent back: “ + sData);
});

« 用XML HTTP 对象进行POST请求 | 首页 | PHP实现文件上传 »

About

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

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

The next post in this blog is PHP实现文件上传.

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