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来把上传来的缓存文件放到我们希望保存的地方。

相关推荐
掘金安东尼7 小时前
纯 CSS 实现弹性文字效果
前端·css
牛奶7 小时前
Vue 基础理论 & API 使用
前端·vue.js·面试
牛奶7 小时前
Vue 底层原理 & 新特性
前端·vue.js·面试
anOnion8 小时前
构建无障碍组件之Radio group pattern
前端·html·交互设计
pe7er8 小时前
状态提升:前端开发中的状态管理的设计思想
前端·vue.js·react.js
SoaringHeart9 小时前
Flutter调试组件:打印任意组件尺寸位置信息 NRenderBox
前端·flutter
晚风予星9 小时前
Ant Design Token Lens 迎来了全面升级!支持在 .tsx 或 .ts 文件中直接使用 Design Token
前端·react.js·visual studio code
sunny_10 小时前
⚡️ vite-plugin-oxc:从 Babel 到 Oxc,我为 Vite 写了一个高性能编译插件
前端·webpack·架构
GIS之路10 小时前
ArcPy 开发环境搭建
前端
林小帅11 小时前
【笔记】OpenClaw 架构浅析
前端·agent