首页 > 解决方案 > 如何在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();
 });
})

这是片段的全部代码。

标签: javascriptjquerynode.jsajax

解决方案


从 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);
        }
    });
}

推荐阅读