XMLHttpRequest API 使用指南
一、实例化 XMLHttpRequest 对象
使用 Ajax API 的第一件事情就是实例化 XMLHttpRequest 对象。
var xhr = new XMLHttpRequest();
二、初始化请求
使用 XMLHttpRequest 对象时,要调用的第一个方法就是 open()。它不会真正发送请求,而只是初始化一个请求准备发送。
open() 方法接受三个参数:请求的类型(“GET”、“POST”等)、请求的资源地址和表示是否发送异步请求的布尔值(默认为 true)。
xhr.open('GET', 'example.php', false);
启动一个同步 GET 请求,请求的资源地址为 example.php。
三、发送请求
xhr.send(null);
send() 方法接受一个参数,表示发送的请求主体数据。如果不需要发送请求主体数据,则必须输入 null,因为这个参数对有些浏览器来说是必需的。
四、GET 请求
HTML 代码:
<div class="content"></div>
JavaScript 脚本:
var xhr = new XMLHttpRequest();
function addURLParam(url, name, value) {
url += (url.indexOf('?') == -1 ? '?' : '&');
url += encodeURIComponent(name) + '=' + encodeURIComponent(value);
return url;
}
xhr.onreadystatechange = function(){
if (xhr.readyState === 4) {
if (xhr.status === 200) {
document.querySelector('.content').innerHTML = xhr.responseText;
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
var url = 'server.php';
url = addURLParam(url, 'author', '张宝');
url = addURLParam(url, 'article', 'XMLHttpRequest API 使用指南');
xhr.open('GET', url, true);
xhr.send(null);
PHP 处理脚本:
if (isset($_GET["author"]) && isset($_GET["article"])) {
echo "GET:《" . $_GET["article"] . "》 by " . $_GET["author"];
}
五、POST 请求
POST 请求把数据作为请求主体提交。
5.1 使用序列化数据
HTML 代码:
<div class="content"></div>
JavaScript 脚本:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4) {
if (xhr.status === 200) {
document.querySelector('.content').innerHTML = xhr.responseText;
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
var url = '../asset/source/server.php';
xhr.open('POST', url);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("foo=bar&lorem=ipsum");
PHP 处理脚本:
if (isset($_POST["foo"]) && isset($_POST["lorem"])) {
echo "POST: foo=" . $_POST["foo"] . "&lorem=" . $_POST["lorem"];
}
5.2 使用序列化后的表单数据
HTML 代码:
<div class="content">
<form id="postForm">
<input type="text" value="bar" name="foo"><input type="text" value="ipsum" name="lorem">
</form>
</div>
JavaScript 脚本:
var xhr = new XMLHttpRequest();
function serialize(form) {
var parts = [],
field = null,
i,
len,
j,
optLen,
option,
optValue;
for (i = 0, len = form.elements.length; i < len; i++) {
field = form.elements[i];
switch (field.type) {
case 'select-one':
case 'select-multiple':
if (field.name.length) {
for (j = 0, optLen = field.options.length; j < optLen; j++) {
option = field.options[j];
if (option.selected) {
optValue = '';
if (option.hasAttribute) {
optValue = (option.hasAttribute('value') ?
option.value : option.text);
} else {
optValue = (option.attributes['value'].specified ?
option.value : option.text);
}
parts.push(encodeURIComponent(field.name) + '=' +
encodeURIComponent(optValue));
}
}
}
break;
case undefined:
case 'file':
case 'submit':
case 'reset':
case 'button':
break;
case 'radio':
case 'checkbox':
if (field.checked) {
break;
}
default:
if (field.name.length) {
parts.push(encodeURIComponent(field.name) + '=' +
encodeURIComponent(field.value));
}
}
}
return parts.join('&');
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
document.querySelector('.content').innerHTML = xhr.responseText;
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
var url = 'server.php';
xhr.open('POST', url);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(serialize(document.getElementById('postForm')));
PHP 处理脚本:
if (isset($_POST["foo"]) && isset($_POST["lorem"])) {
echo "POST: foo=" . $_POST["foo"] . "&lorem=" . $_POST["lorem"];
}
六、FormData 类型
FormData 类型可以用于构造表单数据。
var formData = new FormData();
formData.append('username', '张三');
formData.append('email', 'zhangsan@example.com');
formData.append('birthDate', 1940);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4) {
if (xhr.status === 200) {
document.querySelector('.content').innerHTML = xhr.responseText;
} else {
console.error(xhr.statusText);
}
}
};
xhr.open("POST", "server.php");
xhr.send(formData);
PHP 处理脚本:
if (isset($_POST["username"]) && isset($_POST["email"]) && isset($_POST["birthDate"])) {
echo "POST: username=" . $_POST["username"] . "&email=" . $_POST["email"] . "&birthDate=" . $_POST["birthDate"];
}
七、上传文件
HTML 代码:
<form action="uploadFiles.php" method="post" enctype="multipart/form-data">
<label for="file">文件名:</label>
<input type="file" name="images[]" multiple>
</form><hr>
<div class="content"></div>
JavaScript 代码:
function uploadFiles(url, files) {
var formData = new FormData();
for (var i = 0, file; file = files[i]; ++i) {
formData.append('images[]', file); // 有可选的第三个参数,指定上传文件的文件名
}
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function(e) {
document.querySelector('.content').innerHTML = xhr.responseText;
};
xhr.send(formData);
}
document.querySelector('input[type="file"]').addEventListener('change', function(e) {
uploadFiles('../asset/source/uploadFiles.php', this.files);
}, false);
PHP 服务器处理脚本(在与脚本同级的目录下,新建文件夹 uploads,作为保存上传文件的地方):
for($i = 0; $i< count($_FILES['images']['name']); $i++) {
if ($_FILES['images']["error"][$i] > 0) {
switch($_FILES['images']["error"][$i]) {
case 1:
$err_info="上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值";
break;
case 2:
$err_info="上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值";
break;
case 3:
$err_info="文件只有部分被上传";
break;
case 4:
$err_info="没有文件被上传";
break;
case 6:
$err_info="找不到临时文件夹";
break;
case 7:
$err_info="文件写入失败";
break;
default:
$err_info="未知的上传错误";
break;
}
echo "错误:" . $err_info . "<hr>";
continue;
}
echo "上传文件名: " . $_FILES['images']["name"][$i] . "<br>";
echo "文件类型: " . $_FILES['images']["type"][$i] . "<br>";
echo "文件大小: " . ($_FILES['images']["size"][$i] / 1024) . " kB<br>";
echo "文件临时存储的位置: " . $_FILES['images']["tmp_name"][$i];
echo "<hr>";
$tmpFilePath = $_FILES['images']['tmp_name'][$i];
if ($tmpFilePath != "") {
$newFilePath = "./uploads/" . $_FILES['images']['name'][$i];
move_uploaded_file($tmpFilePath, $newFilePath);
}
}
(完)
XMLHttpRequest API 使用指南的更多相关文章
- Web API 入门指南 - 闲话安全
Web API入门指南有些朋友回复问了些安全方面的问题,安全方面可以写的东西实在太多了,这里尽量围绕着Web API的安全性来展开,介绍一些安全的基本概念,常见安全隐患.相关的防御技巧以及Web AP ...
- RESTful API 设计指南 (转)
RESTful API 设计指南 2016-02-23 ImportNew (点击上方公号,可快速关注) 作者:阮一峰 链接:http://www.ruanyifeng.com/blog/2014/0 ...
- RESTFUL API 安全设计指南
RESTFUL API 安全设计指南 xxlegend · 2015/10/18 15:08 0x01 REST API 简介 REST的全称是REpresentational State Trans ...
- 来自HeroKu的HTTP API 设计指南(中文版)
原文转自:http://get.jobdeer.com/343.get 来自HeroKu的HTTP API 设计指南(中文版) 翻译 by @Easy 简介 本指南中文翻译者为 @Easy ,他是国内 ...
- Web API入门指南(安全)转
安全检测的工具站点:https://www.owasp.org/index.php/Category:Vulnerability_Scanning_Tools Web API入门指南有些朋友回复问了些 ...
- 组件接口(API)设计指南-文件夹
组件接口(API)设计指南-文件夹 组件接口(API)设计指南[1]-要考虑的问题 组件接口(API)设计指南[2]-类接口(class interface) 组件接口(API)设计指南[3]-托付( ...
- Web API 入门指南
Web API 入门指南 - 闲话安全2013-09-21 18:56 by 微软互联网开发支持, 231 阅读, 3 评论, 收藏, 编辑 Web API入门指南有些朋友回复问了些安全方面的问题,安 ...
- RESTFul API设计指南及使用说明
RESTFul API设计指南及使用说明 一. 协议 API与用户的通信协议,使用HTTP协议. 二. 域名 应尽量将API部署在专用域名之下(http://api.example.com) 也可以将 ...
- Google API Design Guide (谷歌API设计指南)中文版
面向资源的设计 这份设计指南的目标是帮助开发人员设计简单.一致.易用的网络API.同时,它也有助于收敛基于socket的API和(注:原文是with,这里翻译为“和”)基于HTTP的REST API. ...
随机推荐
- iOS仿微博客户端一条微博的布局
前言 做一个微博客户端的第三方是自学的第一个实践的项目,自从从事iOS工作之后,就把这个项目给搁置了.趁现在过年回来有些空闲时间,再次修改(总觉得项目就是不停地修改).并且记录一点东西,以后可再回头看 ...
- 卷积神经网络(CNN)模型结构
在前面我们讲述了DNN的模型与前向反向传播算法.而在DNN大类中,卷积神经网络(Convolutional Neural Networks,以下简称CNN)是最为成功的DNN特例之一.CNN广泛的应用 ...
- jsp判断为空用not empty
试过 !='' 不管用,只好百度,现在知道了 <c:if test="${not empty pos.requireDegreeName }"> ${pos.requi ...
- HTML文档及标签介绍
HTML标签 HTML 标记标签通常被称为 HTML 标签 (HTML tag). HTML标签是由尖括号包含的关键词,比如<html> HTML标签通常是成对出现的,比如<body ...
- IOS自定义UIView
IOS中一般会用到几种方式自定义UIView 1.继承之UIView的存代码的自定义View 2.使用xib和代码一起使用的自定义View 3.存xib的自定义View(不需要业务处理的那种) 本文主 ...
- [PKU2389]Bull Math (大数运算)
Description Bulls are so much better at math than the cows. They can multiply huge integers together ...
- wemall软件交易平台微信图文编辑器部分代码分享
wemall软件交易平台微信图文编辑器部分代码,可下载: controller.php <?php date_default_timezone_set("Asia/chongqing& ...
- node.js爬虫爬取拉勾网职位信息
简介 用node.js写了一个简单的小爬虫,用来爬取拉勾网上的招聘信息,共爬取了北京.上海.广州.深圳.杭州.西安.成都7个城市的数据,分别以前端.PHP.java.c++.python.Androi ...
- 获取经纬度 CLLocation
//导入库 #import <CoreLocation/CoreLocation.h> //注意: //需要在 info.plist 中导入前两个字段 //NSLocationAlways ...
- 表格和echart二级联动,并通过点击echart高亮图标单元格
html 部分 <!DOCTYPE html><html><head lang="en"> <meta charset="UTF ...