简体   繁体   English

通过JSON将javascript数组发送到php不起作用

[英]Sending javascript array to php via JSON doesn't work

I have a javascript array and want to send it to the php via form input hidden field. 我有一个javascript数组,并希望通过表单输入隐藏字段将其发送到PHP。 What i'm doing is here: 我在做什么在这里:

html: HTML:

<form method="post" action="a.php" onSubmit="fun();">
    <input type="hidden" name="hiddenF" value="">
</form>

and in javascript: 并在JavaScript中:

function fun()
{
    var jArray = [ "One", "Two", "Three"];

    document.getElementsByName("hiddenF").value = JSON.stringify(jArray);
}

and finally in php that i need an array doing like below but i don't get anything on page. 最后在PHP中,我需要一个像下面这样的数组,但我没有在页面上得到任何东西。

$arr=json_decode($_POST['hiddenF']);
print_r($arr);

document.getElementsByName("hiddenF") returns an array. document.getElementsByName("hiddenF")返回一个数组。 So you need to add [0] to access your hidden input. 所以你需要添加[0]来访问隐藏的输入。

Should be like that: 应该是这样的:

document.getElementsByName("hiddenF")[0].value = JSON.stringify(jArray);

You can also do it by using ID attribute..This will work 你也可以使用ID属性来做这件事。这样可行

<?php
if(isset($_POST["submit"])){
    $arr = json_decode($_POST['hiddenF']);
    print_r($arr);
}
?>

<script type="text/javascript">
function fun()
{
    var jArray = [ "One", "Two", "Three"];
    document.getElementById("hiddenF").value = JSON.stringify(jArray);
}

</script>

<form method="post" action="<?=$_SERVER["PHP_SELF"]?>" onSubmit="fun();">
    <input type="hidden" name="hiddenF" value="" id="hiddenF">
    <input type="submit" name="submit" />
</form>

If you want to make it work with name attribute, go with above answers. 如果您想使用name属性,请使用上面的答案。

The function document.getElementsByName return an array, so you can't change the .value of this array. 函数document.getElementsByName返回一个数组,因此您无法更改此数组的.value

// ...
document.getElementsByName("hiddenF")[0].value = JSON.stringify(jArray);

But I suggest you to use getElementById instead. 但我建议你改用getElementById

HTML: HTML:

<input type="hidden" id="hiddenF" name="hiddenF" value="">

JS: JS:

// ...
document.getElementById("hiddenF").value = JSON.stringify(jArray);

Try this: 尝试这个:

Java Script: Java脚本:

function fun(){
    var jArray = [ "One", "Two", "Three"];
    document.getElementsByName("hiddenF")[0].value = JSON.stringify(jArray);    
}

Html Form: Html表格:

<form method="post" action="process.php" onSubmit="return fun();">
    <input type="hidden" name="hiddenF" value="">
    <input type="submit" value="Submit"/>
</form>

Process.php Process.php

<?php
$arr=json_decode($_POST['hiddenF']);
print_r($arr);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM