javascript - 如何在ajax调用中使用GET请求显示服务器响应的页面
问题描述
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
}
});
}
这是我想在 html 中显示给定 url 的 ajax GET 请求。下面是我的登录逻辑的整个片段。
$(document).ready(()=>{
$('#login').submit((e)=>{
$.ajax({
type: 'POST',
url:'http://localhost:3000/login/users',
data: {
email: $('#email').val(),
password: $('#password').val()
},
success: function(data, status, req){
// alert(req.getResponseHeader('x-auth'));
localStorage.setItem('t',req.getResponseHeader('x-auth'));
var token = localStorage.getItem('t');
regCall(token);
// window.location.href = '/';
},
error: function (req, status, error) {
// alert(req.getResponseHeader('x-auth'));
localStorage.setItem('t',req.getResponseHeader('x-auth'));
alert('Invalid email and password');
window.location.href = '/login';
}
});
e.preventDefault();
});
})
这是片段的全部代码。
解决方案
从 SUCCESS 函数中提取响应数据:
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
},
success: function(data){
//targetElement should be replaced by the ID of target element
$("#targetElement").html(data);
}
});
}
推荐阅读
- c# - 通用 Windows 平台和 .net 核心兼容性
- javascript - Uncaught TypeError: (...).modal 不是 ES6 中的函数
- typescript - 打字稿歧视联盟允许无效状态
- github - 带有 github 页面和 jekyll 的自定义名称域
- php - 管理员用户列表自定义列显示基于 Wordpress 中的自定义用户元数据
- php - 有条件地将键/值对添加到 Woocommerce 中的数组
- javascript - 查找 JSON 的最大值并存储为变量
- php - 如何在 laravel 控制器中访问 MongoDB 游标中返回的数据?
- css - 弹性项目在其行中的项目之后下降(浮动)
- javascript - Javascript ES6:从列表创建一个 id-value 对象