关于js的问题
有谁能回答一下,js如何用post请求出服务器的数据?
具体如下:
就是我想做个网站,里面需要用到一个md编辑器,又不想用开源程序,但md转成html的工具在后端,需要js去获取,我想用post的方式向服务器发送一个md的请求(就是用post方式访问一个网页)然后接受服务器传来的一个json数据?
感谢回答!
有谁能回答一下,js如何用post请求出服务器的数据?
具体如下:
就是我想做个网站,里面需要用到一个md编辑器,又不想用开源程序,但md转成html的工具在后端,需要js去获取,我想用post的方式向服务器发送一个md的请求(就是用post方式访问一个网页)然后接受服务器传来的一个json数据?
感谢回答!
可以用原生的 XMLHttpRequest 去请求
const xhr = new XMLHttpRequest()
xhr.open("post", "/api/xxx")
xhr.onreadystatechange = function(event) {
if (xhr.status == 200) {
const response = JSON.parse(xhr.responseText)
console.log("服务器响应数据: ", response)
}
}
const data = {
name: "张三",
age: 23
}
// 请选择1、2、3的其中一种格式去请求
// 1. json 格式请求
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
xhr.send(JSON.stringify(data))
// 2. urlencode请求
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
const str = Object.keys(data)
.map(key => {
return `${key}=${encodeURIComponent(data[key])}`
})
.join("&")
xhr.send(str)
// 3. form data 请求
const fromData = new FormData()
Object.keys(data).map(key => {
fromData.append(key, data[key])
})
xhr.setRequestHeader("Content-Type", "multipart/form-data;charset=UTF-8")
xhr.send(fromData)
可以使用axios去请求 https://www.npmjs.com/package/axios