AJAX 中的所有可能数据交换






4.75/5 (4投票s)
使用 QueryStrings、HttpHeaders、Post Data 通过 AJAX 发送接收数据的演示应用程序
引言
这是一个使用 QueryStrings、HttpHeaders、Post Data 通过 AJAX 发送接收数据的演示应用程序。
AJAX
您始终可以在互联网上找到有关 AJAX 的所有描述。
AJAX 简述
Ajax 只是一个名称,用于表示一组已存在的工具。
主要部分是 XMLHttpRequest
,一个可以在 JavaScript 中使用的服务器端对象,自 4.0 版本以来在 Internet Explorer 中得到实现。
要从服务器获取数据,XMLHttpRequest
提供了两个方法:
open
:建立连接send
:向服务器发送请求
服务器提供的数据将位于 XMLHttpRequest
对象的属性中:
responseXml
用于 XML 文件,或responseText
用于纯文本文件。
请注意,每个新的数据请求都必须创建一个新的 XMLHttpRequest
对象。
我们必须等待数据可用才能处理它,为此,数据可用性状态由 XMLHttpRequest
的 readyState
属性给出。
XMLHttpRequest 类属性
- readyState:代码的值将依次从 0 变为 4。
0:未初始化
1:已建立连接
2:已收到请求
3:正在处理响应
4:完成 - status:200 表示成功。
404 如果未找到页面。
- responseText:将加载的数据作为字符
string
保存。 - responseXml:保存已加载的 XML 文件,DOM 方法允许提取数据。
- onreadystatechange:属性,其值是一个函数,当分派
readystatechange
事件时会被调用。
XMLHttpRequest 类方法
- open(mode, url, boolean):mode:请求类型,
GET
或POST
。url:文件位置,带路径。
boolean:true
(异步)/false
(同步)。
可选地,可以在参数中添加用户名和密码。 - send("string"):
string
:POST
数据,GET
命令为null
。 - abort():取消当前 HTTP 请求。
- getAllResponseHeaders():检索所有 HTTP 头的返回值。
- getResponseHeader(string):从响应体中检索 HTTP 头的返回值。
string:HTTP 头的名称。 - setRequestHeader(name, value):在请求中添加一个新的 HTTP 头。
name:头的名称/标识符。
value:头的值。
Using the Code
这里有一个简单的函数 'AjaxRequest
',用于执行 AJAX 请求。
function AjaxRequest(ReadyHandler,URL,Method,Params,QueryString,HttpHeaders) {
if (URL == null) { alert("Request URL is Empty"); }
else {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//An anonymous function is assigned to the event indicator.
xmlhttp.onreadystatechange = function() {
//200 status means ok, otherwise some error code is returned, 404 for example
//The 4 state means for the response is ready and sent by the server.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
ResponseText = xmlhttp.responseText; //get text data in the response
ResponseXML = xmlhttp.responseXML; //get xml data in the response
ResponseHeaderJSON = xmlhttp.getResponseHeader
("CustomHeaderJSON"); // Extract Data in http header
ResponseHeaders = xmlhttp.getAllResponseHeaders(); //Get a string
//containing all http headers returned by server
// Make all the results available in the ReadyHandler via prototyping.
ReadyHandler.prototype.ResponseText = ResponseText;
ReadyHandler.prototype.ResponseHeaderJSON = ResponseHeaderJSON;
ReadyHandler.prototype.ResponseXML = ResponseXML;
ReadyHandler.prototype.ResponseHeaders = ResponseHeaders;
// Execute function passed as ReadyHandelr
ReadyHandler();
}
}
//If querystring is provided Attach it to the url
if (QueryString != "") {
var QueryStringData = "";
for (QueryStringAttribute in QueryString) {
QueryStringData = QueryStringAttribute + "=" +
QueryString[QueryStringAttribute] + "&" + QueryStringData;
}
QueryStringData = QueryStringData.substring(0,
QueryStringData.lastIndexOf('&'));
URL = URL + "?" + escape(QueryStringData); //Here is where the
//query string ia attached to the request url.
}
//POST or GET URL of the script to execute.true for asynchronous
//(false for synchronous).
xmlhttp.open(Method, URL, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if (HttpHeaders != "") {
var HttpHeadersData = "";
for (HttpHeaderName in HttpHeaders) {
xmlhttp.setRequestHeader(HttpHeaderName,
HttpHeaders[HttpHeaderName]); // Here the custom headers are added
}
}
//Post data provided then assemble it into single string to be posted to server
if (Params != "") {
var ParamsData = "";
for (ParamName in Params) {
ParamsData = ParamName + "=" + Params[ParamName] + "&" + ParamsData;
}
ParamsData = ParamsData.substring(0, ParamsData.lastIndexOf('&'));
}
xmlhttp.send(ParamsData); //Send the request with the post data
}
}
[您可以在源代码中找到带有足够注释的完整实现。]
它可以更清晰地展示在您的应用程序中使用 AJAX 的方法。
在演示应用程序中,您可以通过更改传递给 'AjaxRequest
' 函数的参数来测试它。

实际上,在文本框中键入的所有代码都将在单击“执行”按钮时作为 JavaScript 代码执行。这是使用 eval()
函数实现的。
FunctionCall = document.getElementById('FunctionCode').value;
eval(FunctionCall);
函数用法
function AjaxRequest(ReadyHandler,URL,Method,Params,QueryString,HttpHeaders)
描述
-> ReadyHandler:AJAX 请求成功完成后要调用的函数。
注意:请求成功完成后,请求的结果将在传递给 ReadyHandler 的函数中提供。
请求结果将在 4 个变量中提供,分别是:ResponseText
:服务器的文本响应。ResponseHeaderJSON
:自定义 HTTP 头字符串值。
此头字符串可能包含单个 string
值,或者您也可以使用 JSON 格式来表示多个值,然后这些值可以在 ReadyHandler
中解析(如示例所示)。
ResponseHeaders
:包含所有响应 HTTP 头的String
。ResponseXML
:服务器的 XML 响应(仅当响应包含有效 XML 时才可用 XML 对象)。
-> URL
:此参数用于指定要将请求发送到的 URL。
-> Method
:请求方法“GET
”/“POST
”。
-> Params
:要发送到服务器的 POST
数据。期望 JSON 格式的键值对。
-> QueryString
:要作为 QueryString
发送到服务器的数据。期望 JSON 格式的键值对。
-> HttpHeaders
:要作为 HTTP Headers 发送的数据。期望 JSON 格式的键值对。
注意:在头中发送数据时,您必须注意只发送 ASCII 字符(charCode 范围在 32 到 126 之间),否则可能会出现意外结果。请参阅 HTTP 的 RFC 文档。
ReadyHandler
可以包含根据响应数据动态更改网页内容的逻辑。
例如,在演示应用程序中,我使用了 'ProcessRequest()
' 作为 Ready Handler,它将响应设置在相应的 <Div>
中。
function ProcessRequest() {
// // Assign the content to the form
document.getElementById('ResponseTextDiv').innerHTML = ResponseText;
document.getElementById('ResponseXMLDiv').innerHTML = ResponseHeaders;
eval("var CustomHeaders = { " + ResponseHeaderJSON + "};");
var header;
var allHeaders = "<br/>";
if (CustomHeaders != "") {
for (header in CustomHeaders) {
allHeaders = allHeaders + CustomHeaders[header] + "<br/>"
}
}
document.getElementById('ResponseHeadersDiv').innerHTML = allHeaders;
}
示例
AjaxRequest(ProcessRequest, 'Handler.ashx','POST',
{ Param1: 'Param1Value', Param2: 'Param2Value', Param3: 'Param3Value' },
{ Query1: 'Q1', Query2: 'Q2', Query3: 'Q3' },
{ Header1: 'H1', Header2: 'H2', Header3: 'H3' }
);
为了处理客户端请求,我实现了一个简单的 **Generic Handler (.ashx)。**
您可以访问 AJAX 请求中客户端浏览器发送的所有数据(查询字符串 + Post Data + HTTP Headers)。
在 Generic handler 中,可以通过 context.Request
对象访问数据。
尽管您可以访问 context.Request.Params[]
中的所有数据,但也可以单独访问数据,如下所示:
- Query String:
context.Request.QueryString[[index/string]]
- Http Headers:
context.Request.Headers[[index/string]]
在示例应用程序中,我所做的只是将请求中收到的数据回显回来,并添加了一个自定义的 HTTP 头。
foreach(string Param in context.Request.Params)
{
ParamsData ="<br/>" + Param + " : " +
context.Request.Params[Param].ToString() + ParamsData;
}
context.Response.Write(ParamsData);
以上几行捕获请求中的数据并将其发送回响应。
要添加额外的自定义 HTTP 头作为响应:
context.Response.AddHeader("CustomHeaderJSON", CustomHeaderJSON);
如您所见,context.Response
对象用于组装要发送回浏览器的响应。
可以使用 context.Response 的不同方法来实现这一点。
'CustomHeaderJSON' 可以包含一个 string
,但我创建了一个 JSON 格式的 string
来支持多个值。这些值随后在客户端使用 JavaScript 进行解析。
我只是使用了 string
连接来创建它,但您也可以使用 http://www.json.org/ 上提供的不同 JSON 解析器/编码器。
您还可以使用 JSON string
s 来通过 AJAX 交换数据。有时使用 JSON 比 XML 更好。使用 JSON 可以传输更少的字节。
关注点
这是 AJAX 的基本实现,并且可以根据需要和可配置性对函数进行调整和修改。
以下是请求和响应的样子[Fiddler 中的 HTTP 请求]。
