2012-04-17 156 views
0

我通过JS Event获取已更改字段的值,并将该数据捕获到temp1数组中,例如,如果您更改字段名称“name”,那么它将获得字段名称“id”并且将它存储到temp1中。但主要问题是我怎样才能将这个数组传递给一个php表单处理页面,在那里我可以得到这个temp1的值。将JS数组传递给PHP页面

我试过使用JSON,但它并没有帮助我。

我试过的代码是:$ .post('/ somepage.php',temp1);但它没有工作。

请帮我解决这个问题。

我在页面中包含jquery.js库。

<script type="text/javascript"> 
    var temp1 = new Array(); 

    function onChangeTest(changeVal) 
    {  
//alert("Field u changed was: " + changeVal.id) 

temp1.push(changeVal.id); 

tmsg = "Fields u changed so far are:" 
for(var i=0;i<temp1.length;i++) 
{ 
//document.write("<b>temp1["+i+"] is </b>=>"+temp1[i]+"<br>"); 
tmsg = tmsg + " " + temp1[i]; 
} 
alert(tmsg); 
} 
//$.post('/somepage.php', temp1); 
</script> 
+0

我猜的jQuery期望param对象(可能包含数组)而不是数组作为ajax参数。 – Bergi 2012-04-17 07:16:19

+0

运行脚本并检查Firebug响应时,在输出到somepage.php中的'var_dump($ _ REQUEST);'是什么? – powtac 2012-04-17 07:16:42

回答

1

这个问题看起来很简单,对我来说,尝试下面的代码,让我知道结果..

function onChangeTest(changeVal) 
{ 
    //alert("Field u changed was: " + changeVal.id) 
    var temp1 = new Array(); 
    temp1.push(changeVal); 

    tmsg = "Fields u changed so far are:" 
    for(var i=0;i<temp1.length;i++){ 
     //document.write("<b>temp1["+i+"] is </b>=>"+temp1[i]+"<br>"); 
     //tmsg = tmsg + " " + temp1[i]; 
     var newHidInp = document.createElement('input'); 
     newHidInp.type = 'hidden'; 
     newHidInp.name = 'outArray[]'; 
     newHidInp.value = temp1[i]; 
     document.frm.appendChild(newHidInp); 
    } 
    return false; 
} 

HTML:

<form name="frm" action="" method="POST" > 
    <tr> 
<td><font color="red">*</font>Name:<input type="text" name="name" id="name" size="25" onkeyup="onChangeTest('name')" /></td> 
<td><font color="red">*</font>Age<input type="text" name="age" id="age" size="25" onkeyup="onChangeTest('age')" /> 
<input type="submit" name="submit" value="SUBMIT"> 
</td> 
</form> 
</body> 
</html> 

PHP:

<?php 
print("<pre>"); 
print_r(array_unique($_POST['outArray'])); 

?> 
+0

thanx a ton !!!像魅力一样工作 – 2012-04-17 13:40:23

1

你需要的是:

$.post("/somepage.php", { 'temp1[]': temp1 }); 

在这里看到的official documentation为好,有各类数据的例子。

+0

它帮助我学了很多东西,谢谢你的链接.. :) – 2012-04-17 13:40:51

0

更改存储更改的方式。如果您将字段ID存储为对象密钥(例如temp1["username"] = true),则可以轻松使用$.post("/somepage.php", temp1)并通过$_POST["username"]等在PHP中读取值。