将变量从javascript传递到php而不使用window.location

时间:2014-02-17 11:07:24

标签: javascript php

我通过单击添加按钮动态创建文本框。在此单击添加按钮时,我将递增计数变量。如何在我的PHP文件中获取此计数值。我尝试过window.location但它不是working.My代码是:

<script>
  var counter=1;
  function generateRow() {
   var count=counter;

    var temp ="<div class='_25'>Answer:<input type='textbox' size='100' id='textbox' name='mytext[]"+counter+"' placeholder='Please enter your answer text here.....'></input><input name='' type='button' value='Delete' /></div>";

    var newdiv = document.createElement('div');
    newdiv.innerHTML = temp + count;

    var yourDiv = document.getElementById('div');

    yourDiv.appendChild(newdiv);

    var js_var=counter++;

    xmlhttp.open("GET","tt.php?js_var="+js_var,true);
    xmlhttp.send(); 
 }
</script>

3 个答案:

答案 0 :(得分:2)

在php文件中

$count_val=$_GET['js_var'];

答案 1 :(得分:0)

由于您要将变量添加到网址,因此可以使用PHP的$_GET方法获取该变量。

$_GET['js_var'];

答案 2 :(得分:0)

像这样实现:

  var counter=1;
  function generateRow() {
   var count=counter;

    var temp ="<div class='_25'>Answer:<input type='textbox' size='100' id='textbox' name='mytext[]"+counter+"' placeholder='Please enter your answer text here.....'></input><input name='' type='button' value='Delete' /></div>";

    var newdiv = document.createElement('div');
    newdiv.innerHTML = temp + count;

    var yourDiv = document.getElementById('div');

    yourDiv.appendChild(newdiv);

    var js_var=counter++;

    // Update your counter Stat in input field
    $('#counter_stat').val( js_var );

    xmlhttp.open("GET","tt.php?js_var="+js_var,true);
    xmlhttp.send(); 
 }

为您的计数器值创建一个HTML输入标记:

// Pass this field's value to PHP
<input type="hidden" name="counter_stat" id="counter_stat" value="1">