Javascript 将变量从JS移动到PHP

Javascript 将变量从JS移动到PHP,javascript,php,ajax,Javascript,Php,Ajax,我目前正在尝试将一个变量从JS移动到PHP 它们被用来做条纹 我知道我可能需要使用AJAX function _goAheadWithCustomerId(c) { console.log('Customer Id is :', c); customerId = c; } 我想将customerId移动到一个PHP文件中 我该怎么做呢?如果不使用AJAX,我能想到的最简单的方法就是使用 window.location.href JS代码 function _goAheadWithCu

我目前正在尝试将一个变量从JS移动到PHP

它们被用来做条纹

我知道我可能需要使用AJAX

function _goAheadWithCustomerId(c) {
  console.log('Customer Id is :', c);
  customerId = c; }
我想将customerId移动到一个PHP文件中


我该怎么做呢?

如果不使用AJAX,我能想到的最简单的方法就是使用

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($\u GET[“customerid”]
来检查是否收到了值

Php代码

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

您可以在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'];

jQuery和
$.ajax
也许?你知道怎么做吗?@tadmani如果你使用jQuery,这就是解决问题的方法。如果不知道,你可以用很难的方法来解决,但是无论哪种情况,你都需要尝试一些东西,我们可以帮助你解决不完整或部分的问题。你这里的东西还不够,我们不知道要移动的变量是什么d和它要去哪一个PHP目的地,即使是粗略地说。这在同一个文档中有效吗?我希望在一个页面中完成这一切。感谢您的快速回复@Parth!
window.location.href='filename.PHP?var='+var;
尝试一下!谢谢!这就是您的意思吗?PHP会是什么样子?这会带来无限的刷新空间p、 ..@parth您是如何调用函数的?在事件中调用函数?我尝试了它,但效果很好。可能文档都包含在一个文档中?或者它包含在异步函数中?很抱歉,我忘了包含参数。