1. 準(zhǔn)備向服務(wù)器發(fā)送數(shù)據(jù)
Ajax 最常見的一大用途是向服務(wù)器發(fā)送數(shù)據(jù)。最典型的情況是從 客戶端發(fā)送表單數(shù)據(jù),即用戶在form元素所含的各個 input 元素里輸入的值。下面代碼展示了一張簡單的表單:
!DOCTYPE html>
html lang="en">
head>
meta charset="UTF-8">
title>基本表單/title>
style>
.table{display: table;}
.row{display: table-row;}
.cell{display: table-cell;padding: 5px;}
.lable{text-align: right;}
/style>
/head>
body>
form id="fruitform" method="post" action="http://127.0.0.1:8080/form">
div class="lable">
div class="row">
div class="cell lable">Apples:/div>
div class="cell">input name="apples" value="5" />/div>
/div>
div class="row">
div class="cell lable">Bananas:/div>
div class="cell">input name="bananas" value="2" />/div>
/div>
div class="row">
div class="cell lable">Cherries:/div>
div class="cell">input name="cherries" value="20" />/div>
/div>
div class="row">
div class="cell lable">Total:/div>
div id="results" class="cell">0 items/div>
/div>
/div>
button id="submit" type="submit">Submit Form/button>
/form>
/body>
/html>
這個例子中的表單包含三個input元素和一個提交button 。這些input元素讓用戶可以指定三種不同的說過各自要訂購多少,button則會將表單提交給服務(wù)器。
1.1 定義服務(wù)器
顯而易見,這里需要為這些示例創(chuàng)建處理請求的服務(wù)器。這里再一次使用Node.js,原因主要是它很簡單,而且用的是Javascript。新建 fruitcalc.js腳本文件如下:
var http = require('http');
var querystring = require('querystring');
function writeResponse(res,data){
var total = 0;
for(fruit in data){
total += Number(data[fruit]);
}
res.writeHead(200,"OK",{
"Content-Type":"text/html",
"Access-Control-Allow-Origin":"http://localhost:63342"
});
res.write('html>head>title>Fruit Total/title>/head>body>');
res.write('p>'+total+' item ordered/p>/body>/html>');
res.end();
}
http.createServer(function(req,res){
console.log("[200] "+req.method+" to "+req.url);
if(req.method == "OPTIONS"){
res.writeHead(200,"OK",{
"Access-Control-Allow-Header":"Content-Type",
"Access-Control-Allow-Methods":"*",
"Access-Control-Allow-Origin":"*"
});
res.end();
}else if(req.url == '/form' req.method == 'POST'){
var dataObj = new Object();
var contentType = req.headers["content-type"];
var fullBody = '';
if(contentType){
if(contentType.indexOf("application/x-www-form-urlencode") > -1){
req.on('data',function(chunk){
fullBody += chunk.toString();
});
req.on('end',function(){
var dBody = querystring.parse(fullBody);
dataObj.apples = dBody["apples"];
dataObj.bananas = dBody["bananas"];
dataObj.cherries = dBody["cherries"];
writeResponse(res,dataObj);
});
}else if(contentType.indexOf("application/json") > -1){
req.on('data',function(chunk){
fullBody += chunk.toString();
});
req.on('end',function(){
dataObj = JSON.parse(fullBody);
writeResponse(res,dataObj);
});
}
}
}
}).listen(8080);
腳本中高亮部分:writeResponse函數(shù)。這個函數(shù)會在提取請求的表單值之后調(diào)用,它負責(zé)生產(chǎn)對瀏覽器的響應(yīng)。當(dāng)前,這個函數(shù)會創(chuàng)建簡單的HTML文檔,效果如下:
![](/d/20211017/6546832f9f6e4f3bdb996f87f43bb1b6.gif)
這個響應(yīng)很簡單,實現(xiàn)效果是讓服務(wù)器計算出了用戶通過form中各個input元素所訂購的水果總數(shù)。服務(wù)器得端腳本的其余部分負責(zé)解碼客戶端用Ajax發(fā)送的各種可能數(shù)據(jù)格式。
1.2 理解問題所在
上面的圖片清楚的描述了想要用Ajax解決的問題。
當(dāng)提交表單后,瀏覽器會在新的頁面顯示結(jié)果。這意味著兩點:
* 用戶必須等待服務(wù)器處理數(shù)據(jù)并生成響應(yīng);
* 所有文檔上下文信息都丟失了,因為結(jié)果是作為新文檔進行顯示的。
這就是應(yīng)用Ajax的理想情形了??梢援惒缴烧埱螅@樣用戶就能在表單被處理時繼續(xù)與文檔進行交互。
2. 發(fā)送表單
向服務(wù)器發(fā)送數(shù)據(jù)的最基本方式是自己收集并格式化它。下面代碼展示了添加到前面的HTML文檔 example.html 的一段腳本。用的就是這種方式:
!DOCTYPE html>
html lang="en">
head>
meta charset="UTF-8">
title>手動收集和發(fā)送數(shù)據(jù)/title>
style>
.table{display: table;}
.row{display: table-row;}
.cell{display: table-cell;padding: 5px;}
.lable{text-align: right;}
/style>
/head>
body>
form id="fruitform" method="post" action="http://127.0.0.1:8080/form">
div class="lable">
div class="row">
div class="cell lable">Apples:/div>
div class="cell">input name="apples" value="5" />/div>
/div>
div class="row">
div class="cell lable">Bananas:/div>
div class="cell">input name="bananas" value="2" />/div>
/div>
div class="row">
div class="cell lable">Cherries:/div>
div class="cell">input name="cherries" value="20" />/div>
/div>
div class="row">
div class="cell lable">Total:/div>
div id="results" class="cell">0 items/div>
/div>
/div>
button id="submit" type="submit">Submit Form/button>
/form>
script>
document.getElementById("submit").onclick = handleButtonPress;
var httpRequest;
function handleButtonPress(e){
//對表單里的button元素而言,其默認行為是用常規(guī)的非Ajax方式提交表單。這里不想讓他發(fā)生,所以調(diào)用了preventDefault方法
e.preventDefault();
var form = document.getElementById("fruitform");
//收集并格式化各個input的值
var formData ="";
var inputElements = document.getElementsByTagName("input");
for (var i = 0; i inputElements.length; i++){
formData += inputElements[i].name + "=" + inputElements[i].value +"";
}
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = handleResponse;
//數(shù)據(jù)必須通過POST方法發(fā)送給服務(wù)器,并讀取了HTMLFormElement的action屬性獲得了請求需要發(fā)送的URL
httpRequest.open("POST",form.action);
//添加標(biāo)頭來告訴服務(wù)器準(zhǔn)備接受的數(shù)據(jù)格式
httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//把想要發(fā)送給服務(wù)器的字符串作為參數(shù)傳遞給send方法
httpRequest.send(formData);
}
function handleResponse(){
if(httpRequest.readyState == 4 httpRequest.status == 200){
document.getElementById("results").innerHTML = httpRequest.responseText;
}
}
/script>
/body>
/html>
效果圖如下:
![](/d/20211017/3703a59fda627f790ff135577036cf35.gif)
服務(wù)器響應(yīng)表單提交后返回的HTML文檔會顯示在同一頁,而且該請求是異步執(zhí)行的。
3. 發(fā)送JSON數(shù)據(jù)
Ajax不止用來發(fā)送表單數(shù)據(jù),幾乎可以發(fā)送任何數(shù)據(jù),包括JavaScript對象表示法(JavaScript Object Notation,JSON)數(shù)據(jù),而它幾乎已經(jīng)成為一種流行的數(shù)據(jù)格式了。Ajax扎根于XML,但這一格式很繁瑣。當(dāng)運行的Web應(yīng)用程序必須傳輸大量XML文檔時,繁瑣就意味著帶寬和系統(tǒng)容量方面的實際成本。
JSON經(jīng)常被稱為XML的“脫脂”替代品。JSON易于閱讀和編寫,比XML更緊湊,而且已經(jīng)獲得了廣泛支持。JSON發(fā)源于JavaScript,但它的發(fā)展已經(jīng)超越了 JavaScript,被無數(shù)的程序包和系統(tǒng)理解并使用。
以下是一個簡單的JavaScript對象用JSON表達的例子:
{"bananas":"2","apples":"5","cherries":"20"}
這個對象有三個屬性:bananas、apples和cherries。這些屬性的值分別是2、5和20。
JSON的功能不如XML豐富,但對許多應(yīng)用程序來說,那些功能是用不到的。JSON簡單、輕量和富有表現(xiàn)力。下面例子演示了發(fā)送JSON數(shù)據(jù)到服務(wù)器有多簡單,修改前例的JavaScript部分如下:
script>
document.getElementById("submit").onclick = handleButtonPress;
var httpRequest;
function handleButtonPress(e){
e.preventDefault();
var form = document.getElementById("fruitform");
var formData = new Object();
var inputElements = document.getElementsByTagName("input");
for(var i=0;iinputElements.length;i++){
formData[inputElements[i].name] = inputElements[i].value;
}
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = handleResponse;
httpRequest.open("POST",form.action);
httpRequest.setRequestHeader("Content-Type","application/json");
httpRequest.send(JSON.stringify(formData));
}
function handleResponse(){
if(httpRequest.readyState == 4 httpRequest.status == 200){
document.getElementById("results").innerHTML = httpRequest.responseText;
}
}
/script>
這段腳本,創(chuàng)建了一個新的Object,并定義了一些屬性來對應(yīng)表單內(nèi)各個input元素的name屬性值。可以使用任何數(shù)據(jù),但 input元素很方便,而且能和之前的例子保持一致。
為了告訴服務(wù)器正在發(fā)送JSON數(shù)據(jù),把請求的Content-Type標(biāo)頭設(shè)為 application/json,就像這樣:
httpRequest.setRequestHeader("Content-Type","application/json");
用JSON對象和JSON格式進行相互的轉(zhuǎn)換。(大多數(shù)瀏覽器能直接支持這個對象,但也可以用下面的網(wǎng)址里的腳本來給舊版的瀏覽器添加同樣的功能:https://github.com/douglascrockford/JSON-js/blob/master/json2.js )JSON對象提供了兩個方法:
![](/d/20211017/809866dc74e620635a2fc0089b65a170.gif)
在上面的例子中,使用了stringify方法,然后把結(jié)果傳遞給XMLHttpRequest 對象的send方法。此例中只有數(shù)據(jù)的編碼方式發(fā)生了變化。提交表單的效果還是一樣。
4. 使用FormData對象發(fā)送表單數(shù)據(jù)
另一種更簡潔的表單收集方式是使用一個FormData對象,它是在XMLHttpRequest的第二級規(guī)范中定義的。
由于原來的Node.js代碼有點問題,此處用C#新建文件 fruitcalc.aspx作為處理請求的服務(wù)器。其cs代碼如下:
using System;
namespace Web4Luka.Web.ajax.html5
{
public partial class fruitcalc : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int total = 0;
if (Request.HttpMethod == "POST")
{
if (Request.ContentType.IndexOf("multipart/form-data") > -1)
{
for (int i = 0; i Request.Form.Count; i++)
{
total += Int32.Parse(Request.Form[i]);
}
}
writeResponse(Response, total);
}
}
private void writeResponse(System.Web.HttpResponse Response, int total)
{
string strHtml;
Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:63342");
strHtml = total + " item ordered";
Response.Write(strHtml);
}
}
}
4.1 創(chuàng)建 FormData 對象
創(chuàng)建FormData對象時可以傳遞一個HTMLFormElement對象,這樣表單里所有的元素的值都會被自動收集起來。示例如下:
!DOCTYPE html>
html lang="en">
head>
meta charset="UTF-8">
title>使用FormData對象/title>
style>
.row{display: table-row;}
.cell{display: table-cell;padding: 5px;}
.lable{text-align: right;}
/style>
/head>
body>
form id="fruitform" method="post" action="http://localhost:53396/ajax/html5/fruitcalc.aspx">
div class="lable">
div class="row">
div class="cell lable">Apples:/div>
div class="cell">input name="apples" value="5" />/div>
/div>
div class="row">
div class="cell lable">Bananas:/div>
div class="cell">input name="bananas" value="2" />/div>
/div>
div class="row">
div class="cell lable">Cherries:/div>
div class="cell">input name="cherries" value="20" />/div>
/div>
div class="row">
div class="cell lable">Total:/div>
div id="results" class="cell">0 items/div>
/div>
/div>
button id="submit" type="submit">Submit Form/button>
/form>
script>
document.getElementById("submit").onclick = handleButtonPress;
var httpRequest;
function handleButtonPress(e){
e.preventDefault();
var form = document.getElementById("fruitform");
var formData = new FormData(form);
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = handleResponse;
httpRequest.open("POST",form.action);
httpRequest.send(formData);
}
function handleResponse(){
if(httpRequest.readyState == 4 httpRequest.status == 200){
document.getElementById("results").innerHTML = httpRequest.responseText;
}
}
/script>
/body>
/html>
當(dāng)然,關(guān)鍵的變化是使用了FormData對象:
var formData = new FormData(form);
其他需要注意的地方是不再設(shè)置Content-Type標(biāo)頭的值了。如果使用FormData對象,數(shù)據(jù)總是會被編碼為multipart/form-data 。本例提交表單后,顯示效果如下:
![](/d/20211017/08c46525b1516aa8fc3a6e5a1e2debb7.gif)
4.2 修改FormData對象
FormData對象定義了一個方法,它允許給要發(fā)送到服務(wù)器的數(shù)據(jù)添加名稱/值對。
![](/d/20211017/fc6eb75237013be3b1a49d90e5b7c586.gif)
可以用append方法增補從表單中收集的數(shù)據(jù),也可以在不使用HTMLFormElement的情況下創(chuàng)建FormData對象。這就意味著可以使用append方法來選擇向客戶端發(fā)送哪些數(shù)據(jù)值。修改上一示例的JavaScript代碼如下:
script>
document.getElementById("submit").onclick = handleButtonPress;
var httpRequest;
function handleButtonPress(e){
e.preventDefault();
var form = document.getElementById("fruitform");
var formData = new FormData();
var inputElements = document.getElementsByTagName("input");
for(var i=0;iinputElements.length;i++){
if(inputElements[i].name != "cherries"){
formData.append(inputElements[i].name,inputElements[i].value);
}
}
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = handleResponse;
httpRequest.open("POST",form.action);
httpRequest.send(formData);
}
function handleResponse(){
if(httpRequest.readyState == 4 httpRequest.status == 200){
document.getElementById("results").innerHTML = httpRequest.responseText;
}
}
/script>
此段腳本里,創(chuàng)建FormData對象時并沒有提供HTMLFormElement對象。隨后用DOM找到文檔里所有的input元素,并為那些name屬性的值不是cherries的元素添加名稱/值對。此例提交表單后,顯示效果如下:
![](/d/20211017/7813fb40c07f3aba688829f2e1deb020.gif)
5. 發(fā)送文件
可以使用FormData 對象和type 屬性為 file 的input 元素向服務(wù)器發(fā)送文件。當(dāng)表單提交時,F(xiàn)ormData對象會自動確保用戶選擇的文件內(nèi)容與其他的表單值一同上傳。下面的例子展示了如何以這種方式使用FormData對象。
!DOCTYPE html>
html lang="en">
head>
meta charset="UTF-8">
title>使用FormData對象發(fā)送文件到服務(wù)器/title>
style>
.row{display: table-row;}
.cell{display: table-cell;padding: 5px;}
.lable{text-align: right;}
/style>
/head>
body>
form id="fruitform" method="post" action="http://localhost:53396/ajax/html5/fruitcalc.aspx">
div class="lable">
div class="row">
div class="cell lable">Apples:/div>
div class="cell">input name="apples" value="5" />/div>
/div>
div class="row">
div class="cell lable">Bananas:/div>
div class="cell">input name="bananas" value="2" />/div>
/div>
div class="row">
div class="cell lable">Cherries:/div>
div class="cell">input name="cherries" value="20" />/div>
/div>
div class="row">
div class="cell lable">File:/div>
div class="cell">input type="file" name="file" />/div>
/div>
div class="row">
div class="cell lable">Total:/div>
div id="results" class="cell">0 items/div>
/div>
/div>
button id="submit" type="submit">Submit Form/button>
/form>
script>
document.getElementById("submit").onclick = handleButtonPress;
var httpRequest;
function handleButtonPress(e){
e.preventDefault();
var form = document.getElementById("fruitform");
var formData = new FormData(form);
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = handleResponse;
httpRequest.open("POST",form.action);
httpRequest.send(formData);
}
function handleResponse(){
if(httpRequest.readyState == 4 httpRequest.status == 200){
document.getElementById("results").innerHTML = httpRequest.responseText;
}
}
/script>
/body>
/html>
此例里,最明顯的變化發(fā)生在 form元素上。添加了input元素后,F(xiàn)ormData對象就會上傳用戶所選的任意文件。
修改 fruitcalc.aspx 的cs文件如下:
using System;
using System.Web;
namespace Web4Luka.Web.ajax.html5
{
public partial class fruitcalc : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int total = 0;
if (Request.HttpMethod == "POST")
{
if (Request.ContentType.IndexOf("multipart/form-data") > -1)
{
for (int i = 0; i Request.Form.Count; i++)
{
total += Int32.Parse(Request.Form[i]);
}
if (Request.Files["file"] != null)
{
HttpPostedFile file = Request.Files["file"];
file.SaveAs(Server.MapPath("/upload/pictures/" + file.FileName));
}
}
writeResponse(Response, total);
}
}
private void writeResponse(System.Web.HttpResponse Response, int total)
{
string strHtml;
Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:63342");
strHtml = total + " item ordered";
Response.Write(strHtml);
}
}
}
此例的顯示效果如下:
![](/d/20211017/2f200090d36dc32f1cc1c212ffe3ba7b.gif)
以上所述是小編給大家介紹的Ajax 高級功能之a(chǎn)jax向服務(wù)器發(fā)送數(shù)據(jù),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
您可能感興趣的文章:- Windows 2008 服務(wù)器安全加固幾個注意事項
- Windows服務(wù)器的基礎(chǔ)安全加固方法(2008、2012)
- 利用ssh實現(xiàn)服務(wù)器文件上傳下載
- Git 教程之服務(wù)器搭建詳解
- 在一臺服務(wù)器上安裝兩個或多個mysql的實現(xiàn)步驟
- 騰訊云CentOS 6.6快速安裝 Nginx服務(wù)器圖文教程
- Nginx服務(wù)器Nginx.com配置文件詳解
- SQL Server成功與服務(wù)器建立連接但是在登錄過程中發(fā)生錯誤的快速解決方案
- 安卓手機socket通信(服務(wù)器和客戶端)
- Linux服務(wù)器下MariaDB 10自動化安裝部署
- dubbo 管理控制臺安裝和使用詳解