uniapp 提交post请求
时间: 2023-07-08 16:54:46 浏览: 56
在 uni-app 中,可以使用 uni.request() 方法来发送 POST 请求。这个方法的使用方式和原生的 XMLHttpRequest 对象类似,你需要指定请求的 URL、请求头、请求数据等信息。
下面是一个示例代码,演示如何使用 uni.request() 发送 POST 请求:
```
uni.request({
url: 'http://example.com/api/login',
method: 'POST',
header: {
'content-type': 'application/json'
},
data: {
username: 'myusername',
password: 'mypassword'
},
success: function(res) {
console.log(res.data);
},
fail: function(err) {
console.log(err);
}
});
```
在这个示例中,我们向 http://example.com/api/login 发送了一个 POST 请求,请求头指定为 JSON 格式,请求数据为 username 和 password。成功回调函数中可以获取到服务器返回的数据,失败回调函数中可以获取到错误信息。你可以根据自己的实际情况修改请求的 URL、请求头和请求数据。
相关问题
uniapp post 提交表单数据
在uniapp中,可以使用uni.request()方法提交表单数据。
示例代码:
```
<template>
<div>
<form @submit.prevent="submitForm">
<input type="text" v-model="name" placeholder="请输入姓名">
<input type="text" v-model="age" placeholder="请输入年龄">
<button type="submit">提交</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
name: '',
age: ''
}
},
methods: {
submitForm() {
uni.request({
url: 'http://example.com/api/submit',
method: 'POST',
data: {
name: this.name,
age: this.age
},
success(res) {
console.log(res.data)
},
fail(err) {
console.log(err)
}
})
}
}
}
</script>
```
在submitForm方法中,使用uni.request()方法提交表单数据。其中,url为接口地址,method为提交方式,data为提交的数据,success为请求成功后的回调函数,fail为请求失败后的回调函数。
需要注意的是,如果接口需要携带header信息,可以在uni.request()方法中添加header属性进行设置。例如:
```
uni.request({
url: 'http://example.com/api/submit',
method: 'POST',
data: {
name: this.name,
age: this.age
},
header: {
'Content-Type': 'application/x-www-form-urlencoded' // 设置header信息
},
success(res) {
console.log(res.data)
},
fail(err) {
console.log(err)
}
})
```
uniapp提交json数据
在uniapp中,可以使用uni.request方法提交JSON数据。具体步骤如下:
1. 将JSON数据转化为字符串。
2. 在uni.request方法的data参数中传入字符串形式的JSON数据。
例如,以下代码将一个JSON对象转化为字符串,并发送POST请求:
```
var data = {name: '张三', age: 18};
var jsonString = JSON.stringify(data);
uni.request({
url: 'http://example.com/api',
method: 'POST',
header: {
'content-type': 'application/json'
},
data: jsonString,
success: function(res) {
console.log(res.data);
}
});
```
其中,'content-type': 'application/json' 表示请求头中的内容类型为JSON格式。