使用GET的AjQuery请求jQuery无法正常工作

时间:2017-11-22 01:19:33

标签: php jquery ajax get dropdownbox

我正在尝试使用带有ajax请求的jquery来发送下拉列表的选择值,以便根据选择显示不同的复选框。

我使用它并且它有效,但是两次发送GET请求并且认为必须有更有效的方式:

success: function(html) {
  window.location.href= "search.php?industry=" + industry + "";
}

以下代码的GET请求有效,并显示复选框,但表单重复,我不明白为什么。 (图片 - https://ibb.co/j7Ag7m

search.php是所有代码所在的位置,我尝试将表单的复选框部分保存在不同的文件中,例如url:“searchData.php”,但同样的事情发生了。

有人能告诉我,我哪里出错了?

<?php 
if(isset($_GET['industry'])) {
  $request = $_GET[‘industry’];
  // insert to database here works
}
?>

<form id="skillsSelectForm" role="form" method="get">
  <select id="industry" name="industry">
    <option value="Administration">Administration</option>
    <option value="Business">Business</option>
    <option value="Charity">Charity</option>
    <option value="Healthcare">Healthcare</option>
  </select>

  <script>
  $('#industry').change(function() {
    var industry = $(this).val();
    $.ajax({
      type: "GET",
      url: "search.php",
      data: { industry: industry },
      success: function(data) {
        $("#results").html(data);
      }
    });
  });
  </script>

  <div id="results"></div>

  <?php
  // change checkboxes displayed based on $request
  if(isset($request)) {
    foreach ($allskills as $skill):
      if($request == $skill['industry']) {
        echo '<label for="'.$skill['skill'].'">
        <input type="checkbox" name="'.$skill['skill'].'" value="'.$skill['skill'].'">&nbsp; '.$skill['skill'].'</label>';
      }
    endforeach;
  }
  ?>

  <input type="submit" name="search" value="Search">

</form>

2 个答案:

答案 0 :(得分:0)

我当然不能说为什么你的代码失败了,因为你的解释对我来说不是那么容易理解,而且因为你提供了不完整的代码或只是代码片段。对不起......: - )

无论如何,肯定不需要window.location.href

所以,我就是这样做的。

解决方案1 ​​

只有页面search.php,表单没有ajax请求。如果更改了复选框,只需提交表单即可。因此,有两种方式提交表单:

  • 通过更改组合框值;
  • 点击&#34; searchButton&#34;。

在页面顶部的PHP代码中,使用以下两种情况进行区分:

$industry = 'Administration'; // Default combobox value.

if (isset($_POST['searchButton'])) { // Form was submitted by clicking on the "searchButton".
    $industry = $_POST['industry']; // Assign the chosen combobox value.
    // ...
} elseif (isset($_POST['industry'])) { // Form was submitted by changing the "industry" combobox value.
    $industry = $_POST['industry']; // Assign the chosen combobox value.
    // ...
}

我用过&#34; POST&#34;对于表单的方法属性(推荐)。其余部分在我的代码中得到了充分的评论。

的search.php

<?php
/*
 * Set the default industry. The value will be overwritten 
 * by the combobox value posted upon the form submission.
 */
$industry = 'Administration';

if (isset($_POST['searchButton'])) { // Form was submitted by clicking on the "searchButton".
    $industry = $_POST['industry']; // Assign the chosen combobox value.

    /*
     * Read the values of the posted skills checkboxes here. In the $_POST they are 
     * saved in an array like this:
     * 
     * [skills] => Array (
     *      [0] => 1
     *      [1] => 3
     * )
     */

    /*
     * Search in db and fetch the searching results into an array.
     * How you search is up to you. I'll use here just an array example.
     */
    $searchResults = [
        [
            'myarraykey1' => 13,
            'myarraykey2' => 'a value',
        //...
        ],
        [
            'myarraykey1' => 25,
            'myarraykey2' => 'other value',
        //...
        ],
        [
            'myarraykey1' => 37,
            'myarraykey2' => 'some other value',
        //...
        ],
    ];
} elseif (isset($_POST['industry'])) { // Form was submitted by changing the "industry" combobox value.
    $industry = $_POST['industry']; // Assign the chosen combobox value.
}

/*
 * If the form was not submitted yet, then $industry has the default value "Administration".
 * Otherwise, if the form was submitted (by clicking on the "searchButton"  or by changing 
 * the "industry" combobox value), $industry has the value of the submitted combobox value.
 * 
 * Fetch the skills list from the db for the selected industry with an sql statement like:
 * "SELECT id, name FROM skills WHERE industry = $industry".
 * Note: use prepared statements!
 * 
 * Let's say, if the form was submitted in one of the two ways, the industry chosen in the 
 * combobox was "Administration" or "Environment".
 * 
 * The if-elseif case bellow is just a simulation of getting skills array based on a non-existent db.
 * In your case, fetch the skills from db and define the $skills array, without any if-elseif statement.
 */
if ($industry === "Administration") {
    $skills = [
        [// 1st record
            'id' => 1,
            'name' => 'Management',
        ],
        [// 2nd record
            'id' => 2,
            'name' => 'Insurance',
        ],
        [// 3rd record
            'id' => 3,
            'name' => 'Financial and control',
        ],
    ];
} elseif ($industry === "Environment") {
    $skills = [
        [// 1st record
            'id' => 1,
            'name' => 'Agronomy',
        ],
        [// 2nd record
            'id' => 2,
            'name' => 'Ansible',
        ],
        [// 3rd record
            'id' => 3,
            'name' => 'Business Case Development',
        ],
    ];
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo</title>

        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                $('#industry').on('change', function () {
                    $('#skillsSelectForm').submit();
                });
            });
        </script>

        <style type="text/css">
            body { padding: 30px; }
            button { padding: 5px 10px; font-size: 14px; background-color: #8daf15; color: #fff; border: none; }
        </style>
    </head>
    <body>

        <h3>Skills Search</h3>

        <form id="skillsSelectForm" action="" method="post">

            <select id="industry" name="industry">
                <option value="Administration" <?php echo $industry === 'Administration' ? 'selected' : ''; ?>>
                    Administration
                </option>
                <option value="Environment" <?php echo $industry === 'Environment' ? 'selected' : ''; ?>>
                    Environment & Agriculture
                </option>
            </select>

            <br/><br/>

            <div id="skillsList">
                <?php
                foreach ($skills as $skill) {
                    $id = $skill['id'];
                    $name = $skill['name'];
                    ?>
                    <label for="skill_<?php echo $id; ?>">
                        <?php echo $name; ?>
                    </label>
                    <input type="checkbox" name="skills[]" id="skill_<?php echo $id; ?>" value="<?php echo $id; ?>" />
                    <br/>
                    <?php
                }
                ?>
            </div>

            <br/>

            <button type="submit" name="searchButton">
                Search
            </button>

        </form>

        <?php
        if (isset($searchResults)) { // The form was not yet submitted by clicking on the "searchButton", so the array doesn't exist yet.
            ?>
            <br/><hr/><br/>

            <div id="searchResults">
                <?php
                if ($searchResults) { // Array is not empty, e.g. search results were found.
                    foreach ($searchResults as $searchResult) {
                        $myArrayValue1 = $searchResult['myarraykey1'];
                        $myArrayValue2 = $searchResult['myarraykey2'];
                        //...
                        ?>
                        <div class="search-result-record">
                            <?php echo $myArrayValue1; ?> &raquo; <?php echo $myArrayValue2; ?>
                        </div>
                        <?php
                    }
                } else { // Array is empty, e.g. no search results found.
                    ?>
                    <span class="no-search-results">
                        No search results found
                    </span>
                    <?php
                }
                ?>
            </div>
            <?php
        }
        ?>

    </body>
</html>

解决方案2

实际上它是一个优雅的。有两页:

  • search.php带有表单和两个(!)ajax调用来获取技能列表;
  • getSkillsList.php,其中包含获取和显示技能列表的代码。

第一个ajax在文档就绪时获取技能列表。第二个ajax获取组合框上的技能列表&#39; onchange事件。

通过点击&#34; searchButton&#34;照常提交表单。

的search.php

<?php
if (isset($_POST['searchButton'])) { // Form was submitted by clicking on the "searchButton".
    $industry = $_POST['industry'];

    /*
     * Read the values of the posted skills checkboxes here. In the $_POST they are 
     * saved in an array like this:
     * 
     * [skills] => Array (
     *      [0] => 1
     *      [1] => 3
     * )
     */

    /*
     * Search in db and fetch the searching results into an array.
     * How you search is up to you. I'll use here just an array example.
     */
    $searchResults = [
        [
            'myarraykey1' => 13,
            'myarraykey2' => 'a value',
        //...
        ],
        [
            'myarraykey1' => 25,
            'myarraykey2' => 'other value',
        //...
        ],
        [
            'myarraykey1' => 37,
            'myarraykey2' => 'some other value',
        //...
        ],
    ];
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo</title>

        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

        <script type="text/javascript">
            function getSkillsList() {
                var industry = $('#industry').val();

                $.ajax({
                    method: 'post',
                    dataType: 'html',
                    url: 'getSkillsList.php',
                    data: {
                        industry: industry
                    },
                    success: function (response, textStatus, jqXHR) {
                        $('#skillsList').html(response);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(textStatus + '<br />' + errorThrown);
                    }
                });
            }

            $(document).ready(function () {
                getSkillsList();

                $('#industry').on('change', function () {
                    getSkillsList()
                });

            });
        </script>

        <style type="text/css">
            body { padding: 30px; }
            button { padding: 5px 10px; font-size: 14px; background-color: #8daf15; color: #fff; border: none; }
        </style>
    </head>
    <body>

        <h3>Skills Search</h3>

        <form id="skillsSelectForm" action="" method="post">

            <select id="industry" name="industry">
                <option value="Administration" <?php echo isset($industry) && $industry === 'Administration' ? 'selected' : ''; ?>>
                    Administration
                </option>
                <option value="Environment" <?php echo isset($industry) && $industry === 'Environment' ? 'selected' : ''; ?>>
                    Environment & Agriculture
                </option>
            </select>

            <br/><br/>

            <div id="skillsList"></div>

            <br/>

            <button type="submit" name="searchButton">
                Search
            </button>

        </form>

        <?php
        if (isset($searchResults)) { // The form was not yet submitted, so the array doesn't exist yet.
            ?>
            <br/><hr/><br/>

            <div id="searchResults">
                <?php
                if ($searchResults) { // Array is not empty, e.g. search results were found.
                    foreach ($searchResults as $searchResult) {
                        $myArrayValue1 = $searchResult['myarraykey1'];
                        $myArrayValue2 = $searchResult['myarraykey2'];
                        //...
                        ?>
                        <div class="search-result-record">
                            <?php echo $myArrayValue1; ?> &raquo; <?php echo $myArrayValue2; ?>
                        </div>
                        <?php
                    }
                } else { // Array is empty, e.g. no search results found.
                    ?>
                    <span class="no-search-results">
                        No search results found
                    </span>
                    <?php
                }
                ?>
            </div>
            <?php
        }
        ?>

    </body>
</html>

getSkillsList.php

<?php
/*
 * Get the industry - the value posted through the ajax 
 * request when the onchange event of the combobox or the window's onload event is raised.
 */
if (isset($_POST['industry'])) {
    $industry = $_POST['industry'];

    /*
     * Fetch the skills list from the db for the selected industry with an sql statement like:
     * "SELECT id, name FROM skills WHERE industry = $industry".
     * Note: use prepared statements!
     * 
     * The if-elseif case bellow is just a simulation of getting skills array based on a non-existent db.
     * In your case, fetch the skills from db and define the $skills array, without any if-elseif statement.
     */
    if ($industry === "Administration") {
        $skills = [
            [// 1st record
                'id' => 1,
                'name' => 'Management',
            ],
            [// 2nd record
                'id' => 2,
                'name' => 'Insurance',
            ],
            [// 3rd record
                'id' => 3,
                'name' => 'Financial and control',
            ],
        ];
    } elseif ($industry === "Environment") {
        $skills = [
            [// 1st record
                'id' => 1,
                'name' => 'Agronomy',
            ],
            [// 2nd record
                'id' => 2,
                'name' => 'Ansible',
            ],
            [// 3rd record
                'id' => 3,
                'name' => 'Business Case Development',
            ],
        ];
    }

    foreach ($skills as $skill) {
        $id = $skill['id'];
        $name = $skill['name'];
        ?>
        <label for="skill_<?php echo $id; ?>">
            <?php echo $name; ?>
        </label>
        <input type="checkbox" name="skills[]" id="skill_<?php echo $id; ?>" value="<?php echo $id; ?>" />
        <br/>
        <?php
    }
}

答案 1 :(得分:0)

我在你的代码中看到你的问题是你在$("#result")元素中将整个页面重新加载到它自己。这就是它看起来像执行两次的原因。

当您的$()。更改事件被触发时,它会获取整个html页面并将其发布在#result div元素中。

您可以尝试使用

来简化GET方法的使用
<form id="skillsSelectForm" role="form" method="get">
    <select id="industry" name="industry">
        <option value="">Select Industry</option>
        <option value="Administration">Administration</option>
        <option value="Business">Business</option>
        <option value="Charity">Charity</option>
        <option value="Healthcare">Healthcare</option>
    </select>
    <div id="ChkList"></div>
    <input type="submit" name="search" value="Search">
</form>


<script> 
    $('#industry').change(function() {
        var industry = $(this).val();
        $.ajax({
          type: "GET",
          url: "getSkillList.php",
          data: { industry: industry },
          dataType: 'json'
          success: function(data) {
            if(data.length <> 0){
                var $elem  = $("#ChkList");
                var output = '';
                $elem.empty(); /* empty before appending the skills list */
                $.each(data, function(a,b){
                    output += "<label>"+b.skill+"</label><input type='checkbox' id='"+b.id+"' name=''><br>";
                })
                $elem.append(output); 
            }
          }
        });
    });
</script>


getSkillList.php

<?php 
    $industry_id = $_POST['industry'];
    /* You connection string here */
    $query = "Select * from skill_list where industry_id = $industry_id";
    $sth = mysqli_query($query);
    $rows = array();
    while($r = mysqli_fetch_assoc($sth)) {
        $rows[] = $r;
    }
    print json_encode($rows); 
    /* return the result of the query  $skilllist in json format */
?>