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

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

如果您想要更改当前页面URL,那么您可以将新的

添加到当前页面,向其添加隐藏的输入元素,然后提交它。

 $('body').append($('
') .attr({'action': yourNewURL, 'method': 'post', 'id': 'replacer'}) .append($('') .attr({'type': 'hidden', 'name': 'param1', 'value': "hello"}) ) .append($('') .attr({'type': 'hidden', 'name': 'param2', 'value': "world"}) ) ).find('#replacer').submit();

或类似的东西

尝试以下function。 适合我。 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(); } 

演示用法

   

希望这可以帮助!

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

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

这似乎是一个不太可能的情况,也许您可​​以评论有关传递的数据及其与Page2内容的关系的更多细节?

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

jquery代码

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

PHP代码(save_session.php)

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

PHP代码(your_link.php)

 $output=$_SESSION["variables"];