【问题标题】:Checkboxes in Form to javascript to php表单中的复选框到 javascript 到 php
【发布时间】:2014-08-10 13:14:43
【问题描述】:

我有一个基于 MySQL 数据的带有动态复选框的表单。提交 DIV 刷新时不使用 JavaScript 闪烁。我正在尝试将表单数据发送到 PHP 以更新 MySQL,但由于缺乏 JavaScript 知识,我经常遇到一个或另一个错误。我目前的尝试(见下文)在 FireBug 中给出了“TypeError:document.multipix_form.pix is undefined”错误。

function multipicupdate(php_file, purpose, where) {
    var request =  getXMLHTTP();        // call the function for the XMLHttpRequest instance
    var a = document.getElementById("optone").value ;
    var b = document.getElementById("table").value ;
    var boxes = document.multipix_form.pix.length
    txt = ""
    for (i = 0; i < boxes; i++) {
        if (document.multipix_form.pix[i].checked) {
            txt = txt + document.multipix_form.pix[i].value + " "
        }
    }

  var  the_data = 'purpose='+purpose+'&var1='+a+'&var2='+b+'&var3='+txt;
  request.open("POST", php_file, true);         // set the request
  request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  request.send(the_data);       // calls the send() method with datas as parameter
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      document.getElementById(where).innerHTML = request.responseText;
    }
  }
}

表单名称是 multipix_form。三个表单输入是 optone (select)、table (select) 和 pix[] (checkbox)。 pix[] 正如我之前所说的那样是动态的。将复选框数据从 JavaScript 传递到 php 让我感到困惑。 我的表单提交是:

<input type="button" onClick="multipicupdate('php/ajaxprocess.php', 'multipix', 'message_profile'); return false;" value="Save changes to this photo">

ajaxprocess.php 将获取表单数据并更新 MySQL。

【问题讨论】:

    标签: javascript php jquery mysql


    【解决方案1】:

    正如您已标记 jQuery,这里有一个 jQuery 解决方案。您可以大大简化此代码。首先,您可以使用serialize() 从该表单中的输入值创建一个查询字符串。然后您可以使用$.ajax 将该信息发送到您需要的页面。试试这个:

    <input type="button" value="Save changes to this photo" id="multipicupdate">
    
    $('#multipicupdate').click(function() {
        $.ajax({
            url: '',
            type: 'POST',
            data: $('#myForm').serialize(), // change the selector as needed
            success: function(data) {
                $('#message_profile').html(data);
            }
        });
    });
    

    【讨论】:

    • 好的,将 #myForm 更改为 #multipix_form(我的表单的 id)并将 url 设置为当前只有“”的 php 脚本,但我没有t 获取复选框数据。我错过了什么吗?
    • 假设这是正确的答案,并且我的复选框数据未序列化的问题是另一回事。谢谢
    【解决方案2】:

    后面需要一个分号

    var boxes = document.multipix_form.pix.length
    

    txt = ""
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多