如何重定向到需要带参数的POST的外部站点?

时间:2017-06-07 14:27:14

标签: javascript

其他要求:

  • 使其成为通用
  • 在新标签页中将其打开
  • 在IE11的新标签页中打开它(更坚固)
  • 将其发布到外部/不同的域

1 个答案:

答案 0 :(得分:0)

问题是我们无法在IE11中POST到命名选项卡跨域。

相反,让我们创建一个文件,使用查询字符串参数构建表单。

现在只需向该文件发出get请求即可。

首先,使用以下代码创建一个名为PostRedirect.htm的文件:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript" src="HTMLClient/Scripts/jquery-2.2.4.min.js"></script>
    <script type="text/javascript">

        //This adapter file allows POSTing to any url via a GET
        //Main advantage of this method is that it is IE11 compatible (posting to new named tab is no longer possible in IE11 w/o adjusting the security policy)

        //Must pass a param called url

        $(document).ready(function () {

            //get all the params from the query string
            var urlParams;
            (window.onpopstate = function () {
                var match,
                    pl = /\+/g,  // Regex for replacing addition symbol with a space
                    search = /([^&=]+)=?([^&]*)/g,
                    decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
                    query = window.location.search.substring(1);

                urlParams = {};
                while (match = search.exec(query))
                    urlParams[decode(match[1])] = decode(match[2]);
            })();

            var postLaunch = function (url, params) {

                var form = document.createElement("form");
                form.setAttribute("method", "post");
                form.setAttribute("action", url);
                for (var i in params) {
                    if (params.hasOwnProperty(i)
                        && i != 'url' //no need to submit the url param itself
                        ) {
                        var input = document.createElement('input');
                        input.type = 'hidden';
                        input.name = i;
                        input.value = params[i];
                        form.appendChild(input);
                    }
                }
                document.body.appendChild(form);
                form.submit();               
            };

            postLaunch(urlParams['url'], urlParams);
        });
    </script>
</body>
</html>

现在您只需使用您选择的参数调用上述文件,如下所示:

    var params = {
        url: 'http://oris.co.palm-beach.fl.us/or_web1/new_sch.asp',
        search_by: 'Official Book/Page',
        RecSetSize: 100,
        PageSize: 20,
        search_entry: '24799-0613'
    };
    window.open('/postredirect.htm?' + $.param(params), '_blank');