1、以get方式发送查询字符串
fetch("server.php?查询字符串"[,{
method:"get",
cache:"no-cache", //设置为不使用缓存
credentials:"include" //设置为使用cookie
}]).then(response=>{
if(response.ok){
response.text().then(text=>{
alert(text);
});
}
});
或
url=new URL("http://webzone.cc/server.php");
url.searchParams.append("myname","wswh");
url.searchParams.append("age",18);
fetch(url).then();
或
params=new URLSearchParams({
myname:"wswh",
age:18
});
fetch(`http://webzone.cc/server.php?${params}`).then();
//内容类型为:application/x-www-form-urlencoded
/*
response.text():返回文本。
response.json():返回json对象。
response.formData():返回FormData对象。
response.blob():返回二进制对象
response.arrayBuffer()
*/
2、以post方式发送查询字符串
fetch("server.php",{
method:"post",
body:"myname=wswh&age=18",
headers:{"Content-Type":"application/x-www-form-urlencoded"}
}).then(response=>{
if(response.ok){
response.text().then(text=>{
alert(text);
});
}
});
或
params1=new URLSearchParams()
params1.append("myname","wswh")
params1.append("age",18)
fetch("server.php",{
method:"post",
body:params1,
headers:{"Content-Type":"application/x-www-form-urlencoded"}
}).then()
//内容类型为:application/x-www-form-urlencoded
3、发送json字符串
fetch("server.php",{
method:"post",
body:JSON.stringify({myname:"wswh",age:18}),//还可以使用'{"myname":"wswh","age":18}'
headers:{"Content-Type":"application/json"}
}).then(response=>{
if(response.ok){
response.text().then(text=>{
alert(text);
});
}
});
//内容类型为:application/json
4、发送xml字符串
fetch("server.php",{
method:"post",
body:"<?xml version='1.0' encoding='utf-8' ?><group><name>wswh</name><age>18</age></group>",
headers:{"Content-Type":"application/xml"}
}).then(response=>{
if(response.ok){
response.text().then(text=>{
alert(text);
});
}
});
//内容类型为:application/xml
5、发送FormData对象
form1=new FormData(document.getElementById("form1")); //或form1=new FormData();
form1.append("myname","wswh");
form1.append("age",18);
form1.append("file1",document.getElementById("file1").files[0]);
fetch("server.php",{
method:"post",
body:form1
}).then(response=>{
if(response.ok){
response.text().then(text=>{
alert(text);
});
}
});
//不需要指定内容类型为:multipart/form-data
6、跨域访问
客户端配置
fetch("server.php",{
method:"get|post",
body:"",
mode:"cors"
}).then(response=>{
if(response.ok){
response.text().then(text=>{
alert(text);
});
}
});
php实现跨域
header("access-control-allow-origin:*"); //*可以替换为具体的一个域名,如http://www.aa.com
header("access-control-allow-headers:origin,x-requested-with,content-type,accept");
header("access-control-allow-methods:get,post,options");
/*
若使用cookie,则需设置
header("access-control-allow-origin:https://webzone.cc");
header("access-control-allow-credentials:true");
*/
asp.net core实现跨域
Startup.cs
(1)在ConfigureServices()方法中加入:
services.AddCors();
(2)在Configure()方法中加入:
app.UseCors(builder=>builder.AllowAnyOrigin() //或WithOrigins()
.AllowAnyHeader() //或WithHeaders()
.AllowAnyMethod();
);
7、发送https请求
fetch直接支持https请求