ajax的基本使用(上传文件)

index.html

复制代码
<html>
    <head>
        <title>js</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    </head>
    <body>
        <div>
            我是显示内容
        </div>
        <div>
            <input type="file" name="myFile" class="file_class"/>
            <button class="ajax_btn">原生ajax</button>
        </div>
        
    </body>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script type="text/javascript" src="./index.js">
    </script>
</html>

index.js

复制代码
$(function(){
$(".ajax_btn").click(function(){
        var xhr = new XMLHttpRequest();
        xhr.open("post","http://localhost",true);
        xhr.onreadystatechange = function(e)
        {
            if(xhr.readyState == 4 && xhr.status == 200)
            {
                console.log(JSON.parse(xhr.responseText));
            }
        }
        var file = $(".file_class")[0].files[0];
        var fd = new FormData();
        fd.append("info","zlx");
        fd.append("fileInfo",file);
        xhr.send(fd);
    });
})

index.php

复制代码
<?php
if($_FILES['fileInfo'])
{
    move_uploaded_file($_FILES['fileInfo']['tmp_name'],"./".$_FILES['fileInfo']['name']);
}
$result = array("code"=>200,"msg"=>$_POST["info"]."上传了图片");
print_r(json_encode($result));
?>

注:

ajax使用FormData对象时,不用再去设置表头Content-type,FormData可以用js来实现form表单上传的对象,通过append来添加传递给后台的值,如,我们这里传了info,值为 zlx,fileInfo,值为一个文件对象,(".file_class")\[0\].files\[0\]用来获取file对象,就是我们选择的文件,需要在PHP中使用_FILES['fileInfo']来获取。

通过浏览器调试模式看到请求头,

这个fileInfo是一个二进制的文件。

通过move_uploaded_file来把上传来的缓存文件放到我们希望保存的地方。

相关推荐
海石4 分钟前
去到比北方更北的地方—2025年终总结
前端·ai编程·年终总结
一个懒人懒人11 分钟前
Promise async/await与fetch的概念
前端·javascript·html
Mintopia17 分钟前
Web 安全与反编译源码下的权限设计:构筑前后端一致的防护体系
前端·安全
输出输入19 分钟前
前端核心技术
开发语言·前端
Mintopia24 分钟前
Web 安全与反编译源码下的权限设计:构建前后端一体的信任防线
前端·安全·编译原理
林深现海44 分钟前
Jetson Orin nano/nx刷机后无法打开chrome/firefox浏览器
前端·chrome·firefox
黄诂多1 小时前
APP原生与H5互调Bridge技术原理及基础使用
前端
前端市界1 小时前
用 React 手搓一个 3D 翻页书籍组件,呼吸海浪式翻页,交互体验带感!
前端·架构·github
文艺理科生1 小时前
Nginx 路径映射深度解析:从本地开发到生产交付的底层哲学
前端·后端·架构
千寻girling1 小时前
主管:”人家 Node 框架都用 Nest.js 了 , 你怎么还在用 Express ?“
前端·后端·面试