使用jQuery传递POST数据时打开URL

Bri*_*ian 5 jquery

是否可以使用jQuery在将帖子数据传递到新页面时更改页面URL?

Poi*_*nty 12

如果您想要更改当前页面URL,那么您可以<form>向当前页面添加新内容,向其添加隐藏的输入元素,然后提交它.

$('body').append($('<form/>')
  .attr({'action': yourNewURL, 'method': 'post', 'id': 'replacer'})
  .append($('<input/>')
    .attr({'type': 'hidden', 'name': 'param1', 'value': "hello"})
  )
  .append($('<input/>')
    .attr({'type': 'hidden', 'name': 'param2', 'value': "world"})
  )
).find('#replacer').submit();
Run Code Online (Sandbox Code Playgroud)

或类似的东西

  • 那么如果你想要替换整个页面,那么Ajax有什么意义呢? (2认同)
  • @Brian - 你想**改变页面**,ajax是专门为了防止**改变页面**.你想要的是一个带有进入新页面的动作的表单,仅此而已.你甚至不需要舔javascript就可以做到这一点,只需要一个`<form action ="/ Page2"method ="POST">` (2认同)

小智 5

尝试以下功能。对我有用。JSON 兼容。

/**
 * Function that will redirect to a new page & pass data using submit
 * @param {type} path -> new url
 * @param {type} params -> JSON data to be posted
 * @param {type} method -> GET or POST
 * @returns {undefined} -> NA
 */
function gotoUrl(path, params, method) {
    //Null check
    method = method || "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    //Fill the hidden form
    if (typeof params === 'string') {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", 'data');
        hiddenField.setAttribute("value", params);
        form.appendChild(hiddenField);
    }
    else {
        for (var key in params) {
            if (params.hasOwnProperty(key)) {
                var hiddenField = document.createElement("input");
                hiddenField.setAttribute("type", "hidden");
                hiddenField.setAttribute("name", key);
                if(typeof params[key] === 'object'){
                    hiddenField.setAttribute("value", JSON.stringify(params[key]));
                }
                else{
                    hiddenField.setAttribute("value", params[key]);
                }
                form.appendChild(hiddenField);
            }
        }
    }

    document.body.appendChild(form);
    form.submit();
}
Run Code Online (Sandbox Code Playgroud)

演示使用

    <script>
        $('#GotoNextPage').on('submit', function(evt){
            evt.preventDefault();

            //Make the data
            var sampleData = new Object();
            sampleData.currentPage = 'We are here';
            sampleData.currentUid = 5;

            gotoUrl("actionPage.php", {'cmd':'nextPage', 'data':sampleData});
        });
    </script>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!