【问题标题】:Passing arrays to php page将数组传递给php页面
【发布时间】:2011-10-13 17:09:19
【问题描述】:

我一直在努力解决这个问题。我无法通过 Internet 找到任何解决方案。

这是代码的一部分:

var params = "nome=" + encodeURI(document.getElementById("nome").value )+
"&email=" + encodeURI(document.getElementById("email").value )+
"&telefone=" + encodeURI(document.getElementById("telefone").value )+
"&produto=" + encodeURI(document.getElementsByName("produto[]") )+
"&quantidade=" + encodeURI(document.getElementsByName("quantidade[]") )+
"&msg=" + encodeURI(document.getElementById("msg").value );
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close"); 

“produto”和“quantidade”是数组,来自一个表单。如何将此值传递给我的 php 页面(我想通过电子邮件发送内容)。

【问题讨论】:

  • HTML 表单没有数组。您能否详细说明您要完成的工作,或者向我们展示您的 HTML?
  • 如果它们是复选框,我相信它可以作为数组传递给 php
  • 有哪些名为produto[]quantidade[]的表单元素

标签: php ajax arrays xmlhttprequest nodelist


【解决方案1】:

使用 jquery serialize() 函数会将您的数组转换为字符串以传递给您的服务器

$('[name=produto]').serialize()

http://api.jquery.com/serialize/

【讨论】:

  • 让 jquery 处理表单序列化/ajax 的东西比尝试自己滚动要容易得多。 +1。
  • 太好了,使用序列化让事情变得简单!太棒了,我的应用程序现在就像一个魅力一样工作。谢谢大家的回复。
【解决方案2】:

如果你这样做,我会短暂记住:(这也是 jQuery 序列化的工作方式)

var myArrayToPost = [1, 2, 3];
var postString = "";
for(<-- Iterate over myArrayToPost -->) {
   postString += "MyArray[]=" + value + "&";
}
<-- Post postString -->

基本上你希望帖子是这样的:

"MyArray[]=FirstValue&MyArray[]=SecondValue&MyArray[]=ThirdValue"

然后 PHP 会自动将其放入 $_POST 的数组中,以便您获取:

$_POST['MyArray'] // which will equal 
                  // array(
                  //   'FirstValue',
                  //   'SecondValue', 
                  //   'ThirdValue'
                  // );

【讨论】:

    【解决方案3】:

    在http请求中传递参数时,每一个都是一对name=value,所以produto=1就是一个参数produto,其值为1。要从 http 请求中获取“数组”,您必须构建多个具有相同名称的参数,例如 produto=1&produto=2& ...

    【讨论】:

    • Ademir, acabei optando pelo "serialize", muito simples e funcional, obrigado.
    • Não conhecia esta solução, creio que vou adotar também, abraços Paulo。
    猜你喜欢
    • 2015-05-17
    • 2018-09-05
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 2013-02-24
    相关资源
    最近更新 更多