使用PHP和HTML5 FormData实现无刷新文件上传教程_php实例
无刷新文件上传是一个常见而又有点复杂的问题,常见的解决方案是构造 iframe 方式实现。
在 HTML5 中提供了一个 FormData 对象 API,通过 FormData 可以方便地构造一个表单请求,并通过 XMLHttpRequest 来发送。通过 FormData 对象发送文件也是可以的,如此则无刷新上传就变的非常简单了。
那么 FormData 怎么使用呢?下面脚本之家对此进行简单的介绍。
1. 构造 FormData 对象
想得到一个FormData对象,很简单:
var fd = new FormData();
FormData 对象只提供了一个方法 append ,用于向对象中添加表单请求参数。
在当前主流浏览器中,可通过如下两种方式获取或修改FormData。
方法一:创建一个空的FormData对象,然后再用append方法逐个添加键值对。示例:
var fd = new FormData(); fd.append("name", "脚本之家"); fd.append("blog", "http://php.net"); fd.append("file", document.getElementById("file"));
这种方法可以不需要 HTML 的表单对象存在。
方法二:取得form元素对象,将它作为参数传入FormData对象中。示例:
var formobj = document.getElementById("form"); var fd = new FormData(formobj);
当然,这里还可以使用 append 方法继续向 fd 中添加其他参数。
2. FormData 发送请求
得到 FormData 对象了,如何发送请求呢? FormData 对象主要用于增强型的 XMLHttpRequest 对象的 send 方法中。参考如下示例:
var xhr = new XMLHttpRequest(); xhr.open("POST" ,"http://php.net" , true); xhr.send(fd); xhr.onload = function(e) { if (this.status == 200) { alert(this.responseText); } };
3. jquery 中使用 FormData
在 jQuery 的 ajax 方法中,也可使用 FormData 方式实现无刷新上传。但要注意参数的设置,参考如下:
$.ajax({ url: "http://php.net", type: 'POST', data: fd, /** *必须false才会自动加上正确的Content-Type */ contentType:false, /** * 必须false才会避开jQuery对 formdata 的默认处理 * XMLHttpRequest会对 formdata 进行正确的处理 */ processData:false }).done(function(result){ console.log(result); }).fail(function(err){ console.log(err); });
4. 一个完整的示例(包含PHP处理示例):
<?php //php 接收表单提交信息并打印 if( isset( $_REQUEST['do']) ){ var_dump($_REQUEST); var_dump($_FILES); die(); } ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>FormData Test - php.net</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> </head> <body> <form id="form"> <input type="file" name="file" id="file" /> <input type="text" name="name" id="" value="脚本之家" /> <input type="text" name="blog" id="" value="http://php.net" /> <input type="submit" name="do" id="do" value="submit" /> </form> <script> $("form").submit(function(e){ e.preventDefault(); //空对象然后添加 var fd = new FormData(); fd.append("name", "脚本之家"); fd.append("blog", "http://php.net"); fd.append("file", document.getElementById("file")); //fd.append("file", $(":file")[0].files[0]); //jQuery 方式 fd.append("do", "submit"); //通过表单对象创建 FormData var fd = new FormData(document.getElementById("form")); //var fd = new FormData($("form:eq(0)")[0]); //jquery 方式 //XMLHttpRequest 原生方式发送请求 var xhr = new XMLHttpRequest(); xhr.open("POST" ,"" , true); xhr.send(fd); xhr.onload = function(e) { if (this.status == 200) { alert(this.responseText); }; }; return; //jQuery 方式发送请求 $.ajax({ type:"post", //url:"", data: fd, processData: false, contentType: false }).done(function(res){ console.log(res); }); return false; }); </script> </body> </html>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

To work on file upload we are going to use the form helper. Here, is an example for file upload.

In this chapter, we are going to learn the following topics related to routing ?

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c
