1. 准备向服务器发送数据
Ajax 最常见的一大用途是向服务器发送数据。最典型的情况是从 客户端发送表单数据,即用户在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则会将表单提交给服务器。
1.1 定义服务器
显而易见,这里需要为这些示例创建处理请求的服务器。这里再一次使用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);
新闻热点
疑难解答
图片精选