我正在寻找使用POST方法将参数从一个页面上的javascript / jquery传递到另一个页面上的PHP的最简单方法。
我应该提到两个页面都是用于wordpress页面的PHP模板,但我想这应该不重要。
会欣赏双方代码的例子。
答案 0 :(得分:3)
$.ajax({
type: 'POST',
url: 'otherpage.php',
data: $('form').serialize(), //you may want to give id of the form which contains elements you want to POST
success: function(){
//code on success
},
dataType: 'html'
});
编辑1 如果你想指定你自己的参数发送然后使用:
$.ajax({
type: 'POST',
url: 'otherpage.php',
data: {
paramname1 : "put_param_value_here",
paramname2 : "put_param_value_here",
paramname3 : "put_param_value_here"
},
success: function(){
//code on success
},
dataType: 'html'
});
编辑2 :如果您只想将自己的参数发布到页面(没有ajax。简单的POST会打开页面然后执行以下操作)
function postToUrl(url, params, newWindow)
{
var form = $('<form>');
form.attr('action', url);
form.attr('method', 'POST');
if(newWindow){ form.attr('target', '_blank'); }
var addParam = function(paramName, paramValue){
var input = $('<input type="hidden">');
input.attr({ 'id': paramName,
'name': paramName,
'value': paramValue });
form.append(input);
};
// Params is an Array.
if(params instanceof Array){
for(var i=0; i<params.length; i++){
addParam(i, params[i]);
}
}
// Params is an Associative array or Object.
if(params instanceof Object){
for(var key in params){
addParam(key, params[key]);
}
}
// Submit the form, then remove it from the page
form.appendTo(document.body);
form.submit();
}
这样打电话: -
postToUrl('otherpage.php', {paramname1: "value_here", paramname2: "value_here"});
上的答案
答案 1 :(得分:2)
您可以使用查询字符串参数
$.post("anotherPage.php?param1=one¶m2=two",function(data){
console.log("data"); //prints yahoo
console.log("success");
});
或
$.post("anotherPage.php",{param1:'one',param2:'two'},function(data){
console.log("data"); //prints yahoo
console.log("success");
});
在php页面
$param1=$_POST['param1'];//gives you one
$param2=$_POST['param1'];//gives you two
echo "yahoo";
修改强>
从评论中没有JamesSmith回答我认为你想在那种情况下重定向到其他页面
<强> page1.php中强>
<script>
location.href='page2.php?param1=one¶m2=two'; // this causes the page to redirect
</script>
<强>使page2.php 强>
<h1><?php echo $_GET['param1']; ?></h1>
<h2><?php echo $_GET['param2']; ?></h2>
又是另一个编辑
您可以在第1页中添加表单并将其发布到第2页
<form action="page2.php" method="post">
<input name="param1" type="text" />
<input name="param2" type="text" />
<input name="submit" value="Submit" type="submit" />
</form>
在page2.php
中<h1><?php echo $_POST['param1']; ?></h1>
<h2><?php echo $_POST['param2']; ?></h2>
答案 2 :(得分:1)
根据回应
,你可以在ajax成功中做你想做的事$.post('server.php', ({parm:"1"}) function(data) {
if (data == 1){
window.href = "your redirecting location";
}
else
{
//do something
}
});