如何在 javascript 中为 XMLHttpRequest 解析 HTML 表单数组和关联数组

问题描述 投票:0回答:0

如何在javascript中传递和处理HTML Form数组和关联数组,使处理后的数据可以通过XMLHttpRequest post到.php做进一步处理?谢谢!

这是我的半伪代码:

<!DOCTYPE html>
<html>
<body>

<h2>The XMLHttpRequest Object</h2>
<p id="result"></p>
 
<form onsubmit = "return process_array(this)">
<input type="text" name="array[]" value="a" /> 
<input type="text" name="array[]" value="b" /> 
<input type="text" name="array[]" value="c" /> 
<input type="number"  name="assoc_array[a]" value=1 />
<input type="number"  name="assoc_array[b]" value=2 />
<input type="number"  name="assoc_array[c]" value=3 />
<input type="submit" value = "process" />
</form >

<script>
function process_array(f) {
  var a=f.elements["array[]"]; //not working
  var b=f.elements["assoc_array[]"]; //not working
   
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("result").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "process.php", false);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("array=" +a+"&assoc_array =" + b); //working or not?
  return false;
}
</script>

</body>
</html>

进程.php

<?php

        if(isset($_POST["array"]) && is_array($_POST["array"])){    
            foreach($_POST["array"] as $key => $value)
            {
              //processing array
            }
        }

    if(isset($_POST["assoc_array"]) && is_array($_POST["assoc_array"])){
        foreach($_POST["assoc_array"] as $key => $value){
            if(is_numeric($value)){
                //processing assoc_array
            }
        }
    }

echo result;
?>

var a=f.elements["数组[]"];

var b=f.elements["assoc_array[]"];

这两行不起作用,导致undefined。恐怕以下内容也不起作用。

xhttp.send("array=" +a+"&assoc_array =" + b)

那么,正确的编码是什么?谢谢!

html arrays forms xmlhttprequest associative
© www.soinside.com 2019 - 2024. All rights reserved.