将变量从JS移动到PHP

时间:2018-05-05 22:20:40

标签: javascript php ajax

我目前正在尝试将变量从JS移到PHP。

它们被用于Stripe。

我知道我可能不得不使用AJAX吗?

function _goAheadWithCustomerId(c) {
  console.log('Customer Id is :', c);
  customerId = c; }

我想将customerId移动到PHP文件。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

在不使用AJAX的情况下,我能想到的最简单方法就是使用

向php页面发送get请求
window.location.href

JS代码

function _goAheadWithCustomerId(c) {
  console.log('Customer Id is :', c);
  customerId = c; 
  window.location.href = "index.php?customerid=" + c;
}

稍后使用php检查if(isset($_GET["customerid"]来检查是否已收到该值。

Php Code

if(isset($_GET["customerid"]))
{
    $c = $_GET["customerid"];
    // use it the way you want.
}

答案 1 :(得分:0)

您可以在AJAX中尝试以下代码。

function sendCustId(c) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     document.getElementById("custDiv").innerHTML = "Customer ID successfully sent to server.";
    }
  };
  xhttp.open("GET", "myPhpScript.php?custId="+c, true);
  xhttp.send();
}

在服务器端,您需要访问变量

$customerId = $_REQUEST['custId'];