Ajax 高级功能之ajax向服务器发送数据

2019-09-14 06:55:38于丽

在上面的例子中,使用了stringify方法,然后把结果传递给XMLHttpRequest 对象的send方法。此例中只有数据的编码方式发生了变化。提交表单的效果还是一样。

4. 使用FormData对象发送表单数据

另一种更简洁的表单收集方式是使用一个FormData对象,它是在XMLHttpRequest的第二级规范中定义的。

由于原来的Node.js代码有点问题,此处用C#新建文件 fruitcalc.aspx作为处理请求的服务器。其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 创建 FormData 对象

创建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>