php服务端测试接口函数:
public function test2()
{
$param = $_REQUEST;
// Content-Type:application/json 时的获取方式
// php7后不再支持$HTTP_RAW_POST_DATA
//$param = json_decode(file_get_contents('php://input'), true);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
return json(['code' => 1, 'msg' => 'hello post', 'param.' => $param]);
} else if ($_SERVER['REQUEST_METHOD'] == 'GET') {
return '这是get,共' . count($param) . '个参数:' . var_export($param,true);
} else {
return $_SERVER['REQUEST_METHOD'];
}
}
跨域问题
// 一般跨域此行即可解决
header("Access-Control-Allow-Origin: *");
// content-type类型为其它类型时(非这三个值application/x-www-form-urlencoded、multipart/form-data、text/plain)
// get请求不会产生此问题
header('Access-Control-Allow-Headers:content-type');
axios
说明:Vue2和Vue3都适用,可独立使用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
<title>Vite App</title>
</head>
<body>
app:<div id="app"></div>
<br />
<script>
// 全局设置请求头
/*
this.axios.defaults.headers = {
'Content-Type' : 'application/x-www-form-urlencoded'
}*/
this.axios.post(
'http://192.168.137.1/public/index.php/ezdeploy/api/test2',
{name:'axios'},
{'headers':{'Content-Type' : 'application/x-www-form-urlencoded'}}, // 内部设置请求头
).then((response) => {
console.log(response.data)
}).catch(function (error) {
console.log('服务器错误');
});
this.axios.get(
'http://192.168.137.1/public/index.php/ezdeploy/api/test2',
{params : {a:1,b:2}},
).then((response) => {
console.log(response.data)
}).catch(function (error) {
console.log('服务器错误');
});
</script>
</body>
</html>
vue-resource
说明:
- vue-resource是Vue.js的一款插件,它可以通过XMLHttpRequest或JSONP发起请求并处理响应。
- vue-resource依赖于vue.js,所以要先引入vue.js
- 目前测试发现此插件不支持Vue3
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
<title>Vite App</title>
</head>
<body>
app:<div id="app"></div>
<br />
<script>
Vue.http.post(
'http://192.168.137.1/public/index.php/ezdeploy/api/test2',
{name:'vue-resource'},
{emulateJSON:true} // 设置使用表单格式提交
).then((response) => {
console.log(response.data)
})
Vue.http.get(
'http://192.168.137.1/public/index.php/ezdeploy/api/test2',
{params : {a:1,b:2}},
).then((response) => {
console.log(response.data)
}).catch(function (error) {
console.log('服务器错误');
})
</script>
</body>
</html>
参考链接:
Vue3 Ajax(axios)
Vue.js Ajax(vue-resource)
vue-resource使用简介:什么是vue-resource?
跨域资源共享 CORS 详解
axios的:请求体编码