1、后端的接口
//上传文件
public function upload_file()
{
header('Access-Control-Allow-Origin:*');
$file = request()->file('file');
$path='D:\phpEnv\www\swoole_test\public\uploads';
$info = $file->move($path);
if (!empty($info)) {
return json(['code'=>1,'msg'=>'上传成功']);
} else {
trace($info->getError);
return json(['code'=>0,'msg'=>'上传失败']);
}
}
//ajax跨域,
public function hello()
{
header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Headers: Authorization, Sec-Fetch-Mode, DNT, X-Mx-ReqToken, Keep-Alive, User-Agent, If-Match, If-None-Match, If-Unmodified-Since, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Accept-Language, Origin, Accept-Encoding");
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE');
header('Access-Control-Max-Age: 1728000');
$data = ['code'=>1,'msg'=>'请求成功','data'=>'欢迎来到php后端世界!'];
return json($data);
}
//ajax跨域带参数
public function hello_b()
{
header('Access-Control-Allow-Origin:*');
$data = Request::param('message');
if(!empty($data)){
return json(['code'=>1,'msg'=>'请求成功,传递参数','data'=>$data]);
}
return json(['code'=>9,'msg'=>'请求成功,参数没有']);
}
2、使用vue-cli搭建的项目
3、html的代码如下:
<template>
<div>
<h2>单独实现ajax请求</h2>
<el-button type="primary" size="big" @click="send">发送ajax请求</el-button>
<el-button type="primary" round size="big" @click="send_b">ajax请求,携带参数!</el-button>
<h2>使用ajax上传图片</h2>
<input name="file" type="file" accept="image/png,image/gif,image/jpeg" @change="update"/>
</div>
</template>
js代码如下:
<script>
import axios from 'axios'
export default {
name: "dianji",
data() {
return {
};
},
methods: {
//ajax请求的写法1,
send(){
axios.get('http://localhost:80/index.php/index/uploadpic/hello')
.then(function (data) {
console.log(data.data);
})
.catch(function(error){
console.log(error);
})
},
//ajax请求写法2,带参数的请求
send_b(){
axios.get('http://localhost:80/index.php/index/uploadpic/hello_b',
{
params:{
message:'这是我传递到后台的参数',
}
})
.then(function (response) {
console.log(response);
})
.catch(function (res) {
console.log(res);
})
},
update (e) { // 上传照片
var self = this;
let file = e.target.files[0];
/* eslint-disable no-undef */
let param = new FormData() ; // 创建form对象
param.append('file', file); // 通过append向form对象添加数据
param.append('chunk', '0'); // 添加form表单中其他数据
console.log(param.get('file')) ;// FormData私有类对象,访问不到,可以通过get判断值是否传进去
let config = {
headers: {'Content-Type': 'multipart/form-data'}
};
// 添加请求头
axios.post('http://localhost:80/index.php/index/uploadpic/upload_file', param, config)
.then(function(response){
console.log(response.data)
})
.catch(function (error) {
console.log(error);
});
}
},
}
</script>
到这里,代码基本完成,只需要到router/index.js文件中,将dianji页面进行注册。需要注意的是:path:“对应自己的文件路径”,
因为我这个点击,不是默认页面,所以需要从默认页面,进行跳转。默认的页面是HelloWorld.vue。html代码和js代码,也可以直接写在HelloWorld.vue中,就省略了跳转的步骤。
需要使用:npm run dev启动vue的项目,
会进到如下页面
需要注意的是:axios.get()或者axios.post(),都需要写自己的路径。例子里写的是我自己本地项目的路径。