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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2367594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:20:31  来源:igfitidea点击:

Open URL while passing POST data with jQuery

jquery

提问by Brian

Is it possible using jQuery to change the page URL while passing post data to the new page?

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

回答by Pointy

If you mean that you want to change the currentpage URL, well then you can add a new <form>to the current page, add hidden input elements to it, and then submit it.

如果您的意思是要更改当前页面的 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();

Or something similar

或者类似的东西

回答by Legolas

Try the following function. Works for me. JSON compatible.

试试下面的功能。为我工作。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();
}

Demo usage

演示使用

    <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>

Hope this helps!

希望这可以帮助!

回答by tbeseda

If you are POSTing data notin a form (because you could simply set the form's action to the current page) and the data being posted isn't directly related to the content of the next page, you can use the callback function of jQuery's .post() methodto redirect the user:

如果您发布的数据不在表单中(因为您可以简单地将表单的操作设置为当前页面)并且发布的数据与下一页的内容没有直接关系,您可以使用jQuery 的回调函数。 post() 方法来重定向用户:

$.post( '/Page2', { 'foo' : 'bar' }, function() {
    window.location.href = '/Page2';
});

This seems like an unlikely situation, maybe you could comment with more details about the data being passed and its relation to the content of Page2?

这似乎不太可能发生,也许您可​​以评论有关正在传递的数据及其与 Page2 内容的关系的更多详细信息?

回答by Fatihd

Save variables into $_SESSIONby using jquery post method

$_SESSION使用 jquery post 方法将变量保存到

jquery code

查询代码

$.post("save_session.php", { out: output }) .done(function(data) {  
location.href='your_link.php';
});

Php code (save_session.php)

PHP代码(save_session.php)

$_SESSION["variables"]=$_POST["out"];

Php code (your_link.php)

PHP代码(your_link.php)

$output=$_SESSION["variables"];

回答by Ayan Bhattacharjee

The trick is use php session to keep the data in the target page

诀窍是使用 php session 将数据保存在目标页面中

AJAX POST

AJAX POST

 $(button).click(function(){
    var s_name=$("#txtbox").val(); 
 $.post("http://localhost/AJAX/save_session.php",
{
  student_name: s_name,

},
function(data){

  location.href='http://localhost/AJAX/result.php';
});

Save Session PHP

保存会话 PHP

<?php
session_start();
$_SESSION["name"]=$_POST['student_name'];

?>

Finally your target page

最后你的目标页面

targetpage.php

目标页面.php

    <?php
  session_start();
  include("config.php");
  $name=$_SESSION["name"];
?>

Now you can use the $name or the variable defined to pass the data

现在您可以使用 $name 或定义的变量来传递数据