【问题标题】:Redirecting to another html page while consuming RESTful API with jQuery使用 jQuery 使用 RESTful API 时重定向到另一个 html 页面
【发布时间】:2018-09-09 22:51:15
【问题描述】:

我在 Spring Boot 上实现了一个 Web 应用程序,在后端我需要实现 RESTful API,而在前端我需要使用 jQuery 来使用它(不幸的是)。 我的主屏幕 (index.html) 只是一个人员列表屏幕:人员姓名列表,每个人都是可点击的。当用户单击列表中任何人的姓名时,应提供人员编辑表单(填写给定人员的数据)。 我在想我的 API 不应该关心重定向的事情,这就是我在控制器中写这个的原因:

@GetMapping("/person/{id}")
public Person findById(@PathVariable String id) {
    Long personId = Long.parseLong(id);
    return personRepository.findOne(personId);
}

在前端,我正在尝试对此端点进行 AJAX 调用,但我不明白在哪里进行重定向部分。 我尝试过这样的事情:

$.ajax({
    type: 'GET',
    url: 'http://localhost:8080/api/person/' + id,
    dataType: "json",
    success: function (data) {
        window.location.href = "personForm.html";
        $('#myDiv').append(data.title);          
    }
});

window.location.href = "personForm.html" 之后的一切都不会发生。除了使用window.location.href似乎是一个丑陋的解决方案。有任何想法吗? 谢谢

【问题讨论】:

    标签: javascript jquery rest spring-boot


    【解决方案1】:

    如果您想模拟 HTTP 重定向,可以使用 location.replace。 例如:

    window.location.replace("http://stackoverflow.com");
    

    顺便说一句,如果你想通过链接模拟点击,你使用location.href

    【讨论】:

      【解决方案2】:

      您无法在重定向后执行 javascript,因为您的当前页面将被卸载。 您可以添加 url 参数,因此重定向到类似
      window.location.href = "personForm.html?"+data.title;.

      在该页面上,您可以使用 window.location.search 从 url 获取数据,并使用该信息编辑您的页面。

      【讨论】:

        【解决方案3】:

        你为什么不给被点击的用户添加一个 id 的 url 参数,然后当你在用户表单页面上通过你已经在做的调用获取该用户的信息,那么你不需要重定向。

        <a href="personForm.html?id=1234">John Smith</a>
        

        【讨论】:

          猜你喜欢
          • 2022-06-16
          • 2013-08-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多