从document.getElementById('name')获取var变量到php变量

时间:2012-10-10 12:04:03

标签: php javascript

  

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

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

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

P.S。我知道脚本代码是客户端和php i服务器端,但我需要这个解决方法所以请帮助..

2 个答案:

答案 0 :(得分:2)

我认为您最好的选择是使用值发出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();'>

答案 1 :(得分:0)

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

  • 您可以生成<form>并提交。
  • 您可以使用Ajax
  • 您可以将location设置为新值
相关问题