【问题标题】:How to send post data and go to url with angularjs?如何发送帖子数据并使用 angularjs 转到 url?
【发布时间】:2019-04-25 08:02:48
【问题描述】:

我有一个使用 angularjs 1.6 和 Java 8 的应用程序。 我想将 POST 数据发送到另一个应用程序并转到该应用程序确定的 url。

域是我的应用程序发送想要轮换服务的公民的数据。另一个应用程序获取这些数据并显示一个带有表单的视图,其中所有字段都使用我发送的数据自动完成。 我必须这样做,因为用户要求这样做。

我尝试了几种方法来做到这一点,例如使用 xmlHttpRequest 但是当我发送帖子时,用户页面没有被重定向(尽管接收状态为 302)。

我尝试过的可能解决方案

$http({
                method: "POST",
                headers: { 
                    ...some headers...
                },
                data : someData,
                url: someExternalUrl
            })
            .then(function(response, headers) {
                //catch the location header of response
                var externalUrl = headers("Location");
                $window.location.href = externalUrl;
            }, 
            function(response) {
                //if fail
            });

另一个:

            var url = someUrl;
            var params = JSON.stringify(jsonObject);
            http.open('POST', url, true);

            //Send the proper header information along with the request
            //http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            //Some other headers

            http.onreadystatechange = function() {//Call a function when the state changes.
                if(http.readyState == 4 && http.status == 200) {
                    alert(http.responseText);
                }
            }
            http.send(params);

我该怎么做?

谢谢!

【问题讨论】:

  • 您可以添加一些用 angularjs 或 javascript 编写的代码吗?
  • 不清楚您是否同时实现服务器和客户端代码。尽管如此,您应该了解状态代码旨在作为发出请求的用户代理的语义指示。看看这个post 可以帮助你。
  • 感谢您回答@FarukT,我编辑了帖子。我只实现客户端代码。
  • @CaioSaldanha,我只实现客户端代码。
  • @PranavVR 你错了,我不想发帖然后重定向。我希望帖子重定向页面,就像您发送表单时一样。

标签: javascript java angularjs post


【解决方案1】:

如果您使用 xmlHttpRequest(或 fetch),302 将不会重定向您的浏览器。您需要检索数据并在您的 post call 完成时执行window.location = 'newUrlHere';

您可以通过多种方式进行操作,这里有两种:

  • 您的 POST 方法返回 302,您查看标题,获取 url 并设置窗口位置;
  • 您的 POST 方法在正文中返回一个对象或字符串,该对象或字符串具有您需要去的新位置。得到它并执行window.location = newLocation;,你就可以开始了。

【讨论】:

  • window.location.replace would be better
  • @George -- 这取决于。如果用户使用replace,则返回按钮不会将用户带回原来的位置。很高兴@Geronimo 知道这两种方法都存在,很难,所以他可以为他的用例做出正确的决定。
  • @SergioMoura -- 感谢您的回答。问题是这样做,它不会是同一个请求。当我发帖时,请求被发送到另一个应用程序,然后当我重定向时(一旦我得到请求的响应)我会发出一个新请求,所以它不会工作
  • @SergioMoura 当接收到来自 XHR POST 请求的 302 响应时,浏览器不是这样工作的。浏览器透明地遵循 302 重定向。阅读Returning redirect as response to XHR request
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-13
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-15
  • 1970-01-01
相关资源
最近更新 更多