一行js 访问post请求
时间: 2023-05-16 15:04:52 浏览: 45
可以使用以下代码访问post请求:
```
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
```
其中,url是post请求的地址,data是要发送的数据。这段代码使用了fetch API来发送post请求,并将返回的数据解析为JSON格式。
相关问题
js发生post请求如何写在一行
可以使用 ES6 中的箭头函数和模板字符串,将 JavaScript 发送 post 请求写在一行,示例代码如下:
```javascript
fetch('http://example.com/api/endpoint', { method: 'POST', body: JSON.stringify({ key: 'value' }), headers: { 'Content-Type': 'application/json' } }).then(response => response.json()).then(data => console.log(data));
```
在上面的示例代码中,使用 fetch 函数发送 post 请求,使用 JSON.stringify 将请求参数转换为 JSON 字符串,并设置请求头的 Content-Type 为 application/json。然后使用箭头函数处理响应结果,将其转换为 JSON 格式并打印到控制台。
layui table post 请求 js
以下是使用 layui table 发送 POST 请求的示例代码:
```javascript
// 渲染表格
var table = layui.table;
table.render({
elem: '#demo',
url: '/api/table/list',
method: 'post', // 使用 POST 请求
cols: [[
{field: 'id', title: 'ID', width: 80},
{field: 'username', title: '用户名', width: 120},
{field: 'email', title: '邮箱'},
{field: 'sex', title: '性别', width: 80, sort: true},
{field: 'city', title: '城市'},
{field: 'sign', title: '签名'},
{field: 'experience', title: '积分', width: 80, sort: true},
{field: 'score', title: '评分', width: 80, sort: true},
{field: 'classify', title: '职业', width: 100},
{field: 'wealth', title: '财富', width: 135, sort: true},
{title: '操作', width: 150, align: 'center', toolbar: '#barDemo'}
]],
page: true,
limit: 10,
height: 'full-220'
});
// 监听工具条
table.on('tool(test)', function(obj){
var data = obj.data;
if(obj.event === 'del'){
layer.confirm('真的删除行么', function(index){
$.ajax({
url: '/api/table/delete',
type: 'POST', // 使用 POST 请求
data: {id: data.id},
success: function(res){
if (res.code === 0) {
obj.del();
layer.close(index);
layer.msg('删除成功');
} else {
layer.msg(res.msg);
}
},
error: function(xhr, errorType, error){
layer.alert('删除失败,请稍后重试', {icon: 2});
}
});
});
}
});
```
其中,`method: 'post'` 表示使用 POST 请求方式,`data: {id: data.id}` 表示发送的数据为一个对象,其中包含有 `id` 属性,值为 `data.id`。你需要将 `url` 和 `data` 修改为你实际使用时的接口地址和发送的数据。