请修改我这段代码<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <div id="app"> <el-button type="primary" @click="addRequest">添加</el-button> <el-input v-model="username" placeholder="请输入内容"></el-input> <el-input v-model="password" placeholder="请输入内容"></el-input> </div> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.0/vue.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script> <!-- 引入样式 --> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <!-- 引入组件库 --> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <script> let MyVue = new Vue({ el: '#app', data() { return { username: "114514", password: "114514", } }, methods: { addRequest: () => { $.ajax({ url: http://localhost:8080/hello, // method: "POST", contentType: 'application/x-www-form-urlencoded', // data:{ // username:MyVue.username, // password:MyVue.password // }, success: (res) => { console.log(JSON.parse(res)); } }) } } }) </script> </body> </html>使得ajax获取response headers中的cookies
时间: 2023-12-31 09:04:18 浏览: 275
-doctype-html-html-lang-en-dir-ltr-head-meta-name:
好的,根据您的需求,我对代码进行了修改,并添加了获取响应头中的 Cookies 的代码:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="app">
<el-button type="primary" @click="addRequest">添加</el-button>
<el-input v-model="username" placeholder="请输入内容"></el-input>
<el-input v-model="password" placeholder="请输入内容"></el-input>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.0/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
let MyVue = new Vue({
el: '#app',
data() {
return {
username: "114514",
password: "114514",
}
},
methods: {
addRequest: function() {
$.ajax({
url: "http://localhost:8080/hello",
type: "POST",
contentType: 'application/x-www-form-urlencoded',
xhrFields: {
withCredentials: true // 允许发送和接收 cookie
},
success: function(res, status, xhr) {
console.log(JSON.parse(res));
console.log(xhr.getResponseHeader('Set-Cookie')); // 获取响应头中的 Cookies
},
error: function(xhr, status, error) {
console.log(error);
}
})
}
}
})
</script>
</body>
</html>
```
需要注意的是,此方法只适用于在同一域名下的请求。如果您需要跨域获取 Cookies,需要在服务器端设置相关的 CORS 配置。另外,由于您的代码中使用了箭头函数,我将其改为了普通函数,以避免出现 this 指向错误的问题。
阅读全文