【问题标题】:What is the best way to obtain many/multiple POST variables in PHP from serialize() AJAX?从 serialize() AJAX 获取 PHP 中的多个/多个 POST 变量的最佳方法是什么?
【发布时间】:2018-04-25 11:10:16
【问题描述】:

我有一个包含许多输入的表单,我使用以下代码将所有表单数据发送到 php proccesing:

HTML:

<form>
<input type="text" name="a" />
<input type="text" name="b" />
<input type="text" name="c" />
<input type="text" name="d" />
<input type="text" name="e" />
<input type="text" name="f" />
<button type="button" onclick="update()">UPDATE</button>
</form>

<!-- HERE I SHOW THE VALUES FROM ABOVE INPUTS -->
<input type="text" id="a" />
<input type="text" id="b" />
<input type="text" id="c" />
<input type="text" id="d" />
<input type="text" id="e" />
<input type="text" id="f" />

JS:

<script>
function update()
{
    var str = $("form").serializeArray();
    $.ajax({  
        type: "POST",  
        url: "update.php",  
        data: str,  
        dataType: 'json',
        success: function(result) 
        {  
            document.getElementById("a").value = result.a;
            document.getElementById("b").value = result.b;
            document.getElementById("c").value = result.c;
            document.getElementById("d").value = result.d;
            document.getElementById("e").value = result.e;
            document.getElementById("f").value = result.f;
        },
        error: function(result){
            console.log("Error:");
            console.log(result);
        }
    });
    // return false;
}

</script>

和更新.php:

<?php
$a = $_POST['a'];
$b = $_POST['b'];
$c = $_POST['c'];
$a = $_POST['d'];
$b = $_POST['e'];
$c = $_POST['f'];

$arr = array(
'a' => $a, 
'b' => $b, 
'c' => $c,
'a' => $d, 
'b' => $e, 
'c' => $f
);

echo json_encode($arr);

?>
  1. 第一个问题: 是否有一种简单的方法可以在 PHP 中传递所有 serialize() 变量,而不是像我在代码中那样编写所有变量?太多了,我认为我必须手动添加所有这些是不行的。

     $a = $_POST['a'];
     $b = $_POST['b'];
     $c = $_POST['c'];
     $d = $_POST['d'];
     $e = $_POST['e'];
     $f = $_POST['f'];
    
  2. 有没有一种捷径可以在多个输入中从 PHP 传递 ajax 结果数组值,而不是使用以下代码?

document.getElementById("a").value = result.a;
 document.getElementById("b").value = result.b;
 document.getElementById("c").value = result.c;
 document.getElementById("d").value = result.d;
 document.getElementById("e").value = result.e;
 document.getElementById("f").value = result.f;

我只想说我在表单上有太多输入,我不想手动添加这些变量。这需要太多时间,而且在获取 id 和名称时很容易出错。

【问题讨论】:

    标签: php jquery ajax forms serialization


    【解决方案1】:

    您可以将表单输入作为数组而不是个人名称传递。含义

    <input name='form[a]' type='text'/>
     <input name='form[b]' type='text'/>
     <input name='form[c]' type='text'/>
     <input name='form[d]' type='text'/>
    

    然后在php中这样做

    echo(json_encode($_POST['form']));
    

    【讨论】:

    • 我会试一试的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2015-02-05
    相关资源
    最近更新 更多