【问题标题】:Getting a var variable from document.getElementById('name') into a php variable [duplicate]将 var 变量从 document.getElementById('name') 获取到 php 变量中
【发布时间】:2012-09-30 21:32:32
【问题描述】:

可能重复:
How to pass JavaScript variables to PHP?
send javaScript variable to php variable

我在文档中有 document.getElementById('name') 字段,它的值由脚本更改,当我发帖(到服务器)时,我想获取 document.getElementById('name') 的当前值) 并将其设置在

$temp= document.getElementById('name');
?>

附言我知道脚本代码在客户端和 php i 服务器端,但我需要这个解决方法,所以请帮忙..

【问题讨论】:

标签: php javascript


【解决方案1】:

我认为您最好的选择是使用这些值发出AJAX 请求。有了这个,您可以将值发送并分配给您的PHP variables

否则,您可以使用COOKIE 等来临时存储该值,然后在下次调用服务器端函数时在服务器端使用它。

Ajax 代码

<script type='text/javascript'>
    function getXMLHTTPRequest() {
    try {
    req = new XMLHttpRequest();
    } catch(err1) {
      try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (err2) {
        try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (err3) {
          req = false;
        }
      }
    }
    return req;
    }



      var http = getXMLHTTPRequest();
       function sendValue() {
    var myurl = "session.php";  // to be present in the same folder
     var myurl1 = myurl;
    var value = document.getElementById('urDIV').value;
      myRand = parseInt(Math.random()*999999999999999);
      var modurl = myurl1+"?rand="+myRand+"url"+value ; // this will set the url to be sent

      http.open("GET", modurl, true);
      http.onreadystatechange = useHttpResponse;
      http.send(null);
    }


    function useHttpResponse() {
       if (http.readyState == 4) {
        if(http.status == 200) {
          var mytext = http.responseText;
          // I dont think u will like to do any thing with the response
          // Once you get the response, you are done.
            }
         }
         else {
             // don't do anything until any result is obtained
            }
        } 
</script>

HTML 部分

// considering you are calling on a button call

<input type='button' onclick='sendValue();'>

【讨论】:

【解决方案2】:

发出一个包含数据的新 HTTP 请求。

  • 您可以生成&lt;form&gt; 并提交。
  • 你可以使用 Ajax
  • 您可以将location 设置为新值

【讨论】:

    猜你喜欢
    • 2012-09-28
    • 2017-09-25
    • 2011-08-08
    • 2010-09-29
    • 2018-12-05
    • 1970-01-01
    • 1970-01-01
    • 2022-08-10
    • 1970-01-01
    相关资源
    最近更新 更多