【问题标题】:Post array from form using xmlhttprequest使用 xmlhttprequest 从表单发布数组
【发布时间】:2014-08-16 08:07:51
【问题描述】:

我有一个 php 生成的表格/表格,带有这样的复选框:

    if ($query) {
if (!mysqli_num_rows($query)) {
    //Empty storage
    echo "There are no items in '$storage'.";
    exit();
} else {
    //form
    echo "<form name='send_parts_form' action='../includes/generatetab.php' method='post'>";
    //Table header
    echo "
        <table>
        <tr>
            <th>Part</th>
            <th>PN</th>
            <th>Manufactured</th>
            <th>Serial</th>
            <th>Site</th>
            <th>Date replaced</th>
            <th>By user</th>
            <th>Faulty</th>
            <th>Send</th>
            <th>Select</th>
        </tr>";
    //Retrieved data
    while ($row = mysqli_fetch_array($query)) {
        echo "<tr>";
        echo "<td>" . $row['part_type'] . "</td>";
        echo "<td>" . $row['pn'] . "</td>";
        echo "<td>" . $row['manufactured'] . "</td>";
        echo "<td>" . $row['serial'] . "</td>";
        echo "<td>" . $row['site_id'] . "</td>";
        echo "<td>" . $row['date'] . "</td>";
        echo "<td>" . $row['user'] . "</td>";
        echo "<td>" . $row['faulty'] . "</td>";
        echo "<td><input type='checkbox' name='send_parts[]' class='checkclass' value=" . $row['id'] . "></td>";
        echo "</tr>";};
    echo "</table>";
    echo "</br>";
    echo "</br>";
    echo "<input type='button' onclick='sendToZG()' value='Send'/>";
    echo "</br>";
    echo "<input type='submit' name='submit' value='Generate tab' />";
    echo "</form>";
    exit();
}
    } else {
    die("Query failed");
   }

然后,用户检查他们想要的选项,并在提交(生成选项卡)时获得选项卡分隔的文本以及他们选择的值。 我现在希望当他们单击“发送”时将值发布到另一个 php 页面并在同一页面上返回结果(在 SentList div 下)。我有这样的js:

    //Browser Support Code
    function sendToZG(){
var ajaxRequest;  // The variable that makes Ajax possible!

    try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
    }catch (e){
    // Internet Explorer Browsers
    try{
    ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    }catch (e) {
    try{
     ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }catch (e){
     // Something went wrong
     alert("Your browser broke!");
     return false;
    }
    }
    }

    ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
    var ajaxDisplay = document.getElementById('SentList');
    ajaxDisplay.innerHTML = ajaxRequest.responseText;
    }
    }

    // Now get the value from page and pass it to server script.
    var formData = new FormData( document.getElementsByName("send_parts")[0] );
    ajaxRequest.open('POST', "../includes/sendtozg.php", true);
    ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    ajaxRequest.send("send_parts=" + formData);
    }

编辑:ajaxRequest.send("send_part=" + formData);到 ajaxRequest.send("send_parts=" + formData); 现在它返回:

在第 53 行为 foreach() 提供的参数无效(这是我在 sendtozg.php 中获取数据的地方)。

我会在文章末尾添加 sendtozg.php。

如果不是:

    <form name='send_parts_form' action='../includes/generatetab.php' method='post'>

我回应:

    <form name='send_parts_form' action='../includes/sendtozg.php' method='post'>

提交后,脚本 sendtozg.php 可以正常执行,但在不同的页面上。

所以基本上我要做的是为 php 生成的表单提供 2 个选项:

  1. 生成制表符分隔的 txt 文件
  2. 执行 sendtozg.php 并在同一页面返回结果

我已经有了两个脚本(generatetab.php 和 sendtozg.php),它们工作正常。

sendtozg.php:

    if (!empty($_POST['send_parts'])){
foreach ($_POST['send_parts'] as $send_parts){
$getchecked = mysqli_query($con, "SELECT * FROM $storage WHERE id=$send_parts");
while ($row = mysqli_fetch_array($getchecked)) {
    $copypart = mysqli_query($con, "INSERT INTO sent_parts (part_type, pn, manufactured, serial, site_id, date, user, faulty, log)
                                    SELECT part_type, pn, manufactured, serial, site_id, date, user, faulty, log 
                                    FROM $storage WHERE id=$send_parts");                                       

    // check to see if it copied
    $getserial = mysqli_query($con, "SELECT serial FROM $storage WHERE id=$send_parts");
    $getserial_row = mysqli_fetch_array($getserial, MYSQLI_NUM);
    $foundserial = $getserial_row[0];
    $checkcopy = mysqli_query($con, "SELECT id FROM sent_parts WHERE serial = '$foundserial'");

    // add user info and date
    $addinfo = mysqli_query($con, "UPDATE sent_parts SET sent2zg='$user', date2zg='$strdate' WHERE serial = '$foundserial'");

    if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
    };

    //delete from storage
    if($checkcopy > 0) {
        $getpart = mysqli_query($con, "SELECT part_type FROM sent_parts WHERE serial='$foundserial'");
        $getpart_row = mysqli_fetch_array($getpart, MYSQLI_NUM);
        $deletedpart = $getpart_row[0];
        $removepart = mysqli_query($con, "DELETE FROM $storage WHERE id = '$send_parts'");
        echo "Part " . $deletedpart . " has been transfered";
    } else {
        echo "Part " . $row['part_type'] . "was NOT transfered";
    };      
};
    } exit ();
    } else {
echo "Nothing was selected, please try again!";
    }

【问题讨论】:

  • 您是否尝试过制作第三个 PHP 文件,仅使用 include '../includes/generatetab.php';include '../includes/sendtozg.php';,然后将表单发送到该文件?
  • 不会同时执行这两个脚本吗?我想把它们分开,所以可以单独执行。
  • 啊,我明白了,根据用户操作执行generatetab.phpsendtozg.php。对吗?
  • 是的,没错!它们都可以通过 xmlhttprequest 或其他方式执行。重要的是sendtozg.php在同一页面上返回结果,generatetab.php无论如何都会下载txt文件。

标签: php forms xmlhttprequest


【解决方案1】:

您的&lt;form&gt; 上没有id 属性,因此您需要将id="send_parts" 添加到&lt;form&gt;,或者您需要将您的代码从getElementById 更改为@987654326 @像这样:

// Now get the value from page and pass it to server script.
// Serialize the data
var formData = new FormData( document.getElementsByName("send_parts")[0] );
ajaxRequest.open('POST', "../includes/sendtozg.php", true);
ajaxRequest.send(formData);

然后在 sendtozg.php 中,您需要将前两行更改为:

if (!empty($_POST)){
  foreach ($_POST as $send_parts){

【讨论】:

  • 试过了,但现在打印出来了:在第 53 行为 foreach() 提供的参数无效(这是我在 sendtozg.php 中获取数据的地方)。你可以看看我编辑的帖子。我包括了 sendtozg.php
  • @spiro2903 查看我的编辑,其中解释了如何更改 sendtozg.php。
  • 你写的都做了,然后我得到了“WebKitFormBoundary”,所以我在 sendtozg.js 中删除了“ajaxRequest.setRequestHeader”,然后在 sendtozg.php 中的“$getchecked=...”行出现错误所以我将 id=$send_parts 更改为 id='$send_parts'。现在我没有得到任何结果或打印输出。
  • 如果我添加: print_r ($send_parts);在 foreach 之后和 $getchecked 之前,选择了一项,我得到:数组( [0] => 10 )。我还添加了: ajaxRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");到 sendtozg.js
  • 解决了,sendtozg.php 应该是: if (!empty($_POST)){ foreach ($_POST['send_parts'] as $send_parts){ 感谢帮助。我给你解决办法。
【解决方案2】:

这是 sendtozg.js 的最终代码:

// Get get the value from page and pass it to server script.
var formData = new FormData( document.getElementsByName("send_parts")[0] );

ajaxRequest.open('POST', "../includes/sendtozg.php", true);
ajaxRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
ajaxRequest.send(formData);
}

sendtozg.php 应该是:

    if (!empty($_POST)){
    foreach ($_POST['send_parts'] as $send_parts){
    $getchecked = mysqli_query($con, "SELECT * FROM $storage WHERE id=$send_parts");

顺便说一句:

    print_r ($some_array)

    if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
    };

是很好的故障排除工具。

【讨论】:

    猜你喜欢
    • 2013-09-06
    • 2018-05-01
    • 2012-06-19
    • 2011-09-03
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    相关资源
    最近更新 更多