将一个页面上的JS/Jquery参数传递到另一个页面上的PHP


Passing parameters from JS/Jquery on one page to PHP on another

我正在寻找最简单的方法来使用POST方法从一个页面上的javascript/jquery传递参数到另一个页面上的PHP。

我应该提到这两个页面都是wordpress页面的PHP模板,但我想这应该无关紧要。

感谢两边的代码示例

$.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'
});

Edit 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"});

代码取自JavaScript post请求的答案,如表单提交

可以使用查询字符串参数

$.post("anotherPage.php?param1=one&param2=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";

编辑

从评论没有jamesssmith回答,我认为你想重定向到其他页面在这种情况下

Page1.php

<script>
location.href='page2.php?param1=one&param2=two'; // this causes the page to redirect
</script>

page2.php

<h1><?php echo $_GET['param1']; ?></h1>
<h2><?php echo $_GET['param2']; ?></h2>

又一次编辑

你可以在page1中有一个表单并将其发布到page2

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

您可以根据响应在ajax成功中做您想做的事情

$.post('server.php', ({parm:"1"}) function(data) {
    if (data == 1){
        window.href = "your redirecting location";
    }
    else
    {
        //do something
    }
});