使用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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
