简体   繁体   English

选择选项后使用ajax过滤数据

[英]Filter data with ajax after select option

I am trying to use ajax to filter the data after an option is selected. 我试图在选择选项后使用ajax过滤数据。 Here is html code: 这是html代码:

<select name="filter" onchange="filter(this.value)">
  <option disabled selected>Sort By</option>
  <option value="all">All Artists</option>
  <option value="new">Free Artists</option>
</select>

In the jquery code, I am trying to print filtered data in accordion: 在jQuery代码中,我试图按手风琴打印过滤的数据:

<link rel="stylesheet" type="text/css" href="jquery-ui/jquery-ui.css"/>
<script type="text/javascript" src="jquery-ui/jquery.js"></script>
<script type="text/javascript" src="jquery-ui/jquery-ui.js"></script>

$(document).ready(function(){
    function filter(item)
    {
        $.ajax({
            type: "POST",
            url: "filter2.php",
            data: { value: item},
            success:function(data){
                    document.getElementById('getData').style.display = "block";
                    document.getElementById("getData").innerHTML = response;
                    $('#hideData').hide();
                     $("#myAccordion").accordion({heightStyle:"content", collapsible:true});
                        $("#myAccordion li ").draggable({
                            appendTo: "body",
                            helper: "clone",
                             refreshPositions: true,
                             start: function (event, ui) {
                                sourceElement = $(this);
                            },          
                        });
            }
        });
    }
});

And filter2.php where I try to print names: 还有filter2.php ,我尝试在其中打印名称:

require_once('inc/database_connection.php');
include 'model/model.project.php';
include 'model/model.filter.php';
$fieldname = $_POST['value'];
if($fieldname=="all")
{
    $result1 = getAll();
    while($row1=mysqli_fetch_array($result1))
    {
        $name = $row1['username'];
        echo '<div id="getData">';
        echo '<ul class="source">';
        echo "<li class='item'><span class='closer'>x</span>".$name."</li>";
    }
        echo '</ul>';
        echo '</div>';
}
else if($fieldname=="new")
{
    $result2 = getFree();
    while($row2=mysqli_fetch_array($result2))
    {
        $name = $row2['username'];
        $color = $row2['color'];
        echo '<div id="getData">';
        echo '<ul class="source">';
        if($color=0)
        {
            echo "<li class='item'><span class='closer'>x</span>".$name."</li>";            
        }       
    }
        echo '</ul>';
        echo '</div>';      
}

So the problem is it doesnt work. 所以问题是它不起作用。 I dont get any reaction after choosing option. 选择选项后,我没有任何反应。

jquery provide a .load function that you can use to load your div. jQuery提供了一个.load函数,可用于加载div。 So i am using the same function for more about this function refer to this link http://api.jquery.com/load/ Here the solution i think this might help you, Here's the HTML 因此,我正在使用同一功能,以获取有关此功能的更多信息,请参考此链接http://api.jquery.com/load/在这里,我认为这可能对您有所帮助的解决方案,这是HTML

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<select name="filter" onchange="filter(this.value)">
<option disabled selected>Sort By</option>
<option value="all">All Artists</option>
<option value="new">Free Artists</option>
</select>

<div id="div1"></div>
</body>
</html>
<script>
 function filter(item) {
    $("#div1").load("filter.php", {value: item});
 }
</script>

and Now Here's the php code 现在这是PHP代码

require_once('inc/database_connection.php');
include 'model/model.project.php';
include 'model/model.filter.php';
$fieldname = $_REQUEST['value'];
if (isset($fieldname)) {
if ($fieldname == "all") {

    $result1 = getAll();
    while($row1=mysqli_fetch_array($result1))
    {
        $name = $row1['username'];
        echo '<div id="getData">';
        echo '<ul class="source">';
        echo "<li class='item'><span class='closer'>x</span>".$name."</li>";
    }
    echo '</ul>';
    echo '</div>';
} else if ($fieldname == "new") {

    $result2 = getFree();
    while($row2=mysqli_fetch_array($result2))
    {
        $name = $row2['username'];
        $color = $row2['color'];
        echo '<div id="getData">';
        echo '<ul class="source">';
        if($color=0)
        {
            echo "<li class='item'><span class='closer'>x</span>".$name."</li>";
        }
    }
    echo '</ul>';
    echo '</div>';
}
}

Simply, you shouldn't put your functions inside $(document).ready(function(){ }); 简而言之,您不应该将函数放在$(document).ready(function(){ }); So after removing it the final JavaScript code will be if still have any problem let me know 因此,将其删除后,最终的JavaScript代码将会是如果仍然有任何问题,请通知我

function filter(item) {
    $.ajax({
        type: "POST",
        url: "filter2.php",
        data: {value: item},
        success: function(data) {
            alert(data);
            document.getElementById('getData').style.display = "block";
            document.getElementById("getData").innerHTML = response;
            $('#hideData').hide();
            $("#myAccordion").accordion({
                heightStyle: "content",
                collapsible: true
            });
            $("#myAccordion li ").draggable({
                appendTo: "body",
                helper: "clone",
                refreshPositions: true,
                start: function(event, ui) {
                    sourceElement = $(this);
                },
            });
        }
    });
}

You need to structure and simplify your code, here are the obvious errors that can be spotted from your code : 您需要结构化和简化代码,这是可以从您的代码中发现的明显错误:

The filter function shouldn't be inside the DOM ready event handler : filter函数不应位于DOM ready事件处理程序中:

$(document).ready(function(){
function filter(item)
{ ...

Also, 也,

    while($row1=mysqli_fetch_array($result1)){
    $name = $row1['username'];
    echo '<div id="getData">';
    echo '<ul class="source">';
    echo "<li class='item'><span class='closer'>x</span>".$name."</li>";
    }

You are echoing multiple times (for each row), where you should only do it once. 您正在回声多次(对于每一行),在此仅应执行一次。

Also this is not a test, 0 is affected to $color instead of being tested against: 同样这不是测试,0会影响$ color而不是针对:

if($color=0) // should be  ($color == 0)

Now, to simplify what you are trying to acheive let's recreate filter2.php : 现在,为了简化您要实现的目标,让我们重新创建filter2.php:

function getAll() // this is just to mimic your 'all' data
{
    return array(
        array('username' => 'User 1', 'color' => 'red'),
        array('username' => 'User 2', 'color' => 0),
        array('username' => 'User 3', 'color' => 'red'),
        array('username' => 'User 4', 'color' => 0),
        array('username' => 'User 5', 'color' => 'red'));
}

function getFree() // this is just to mimic your 'free' data source
{
    return array(
        array('username' => 'User 2', 'color' => 0),
        array('username' => 'User 4', 'color' => 0));
}

$results = array();
$fieldname = $_POST['value'];
if ($fieldname == "all") // at a first stage you only need to check which data to use/fetch from the database
    $results = getAll();
elseif ($fieldname == "new")
    $results = getFree();

// now you have the data, you have to output the desired html for the accordion, I followed the regular jQuery layout so you can test it
while($result=array_pop($results)) { // change array_pop back to mysqli_fetch_array($results)
    echo "<h3>$result[username]</h3>
                <div>
                    <p>
                        $result[username]
                    </p>
                </div>";
}

And the front end would look like : 前端看起来像:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Accordion - Test</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        $( function() {
            $( "#myAccordion" ).accordion();
        } );
    </script>
</head>
<body>

<select name="filter" onchange="filter(this.value)">
    <option disabled selected>Sort By</option>
    <option value="all">All Artists</option>
    <option value="new">Free Artists</option>
</select>

<div id="myAccordion"></div>

<script>
    function filter(item)
    {
        $.ajax({
            type: "POST",
            url: "filter2.php",
            data: { value: item},
            success:function(data){
                $('#myAccordion').html(data).accordion( "refresh" );
            }
        });
    }
</script>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 基于多个 Select 选项和 ajax jquery ZE1BFD762321E409CEE4AC0B6E - Filter Data based on Multiple Select option with ajax jquery php jquery 在 select 选项上的搜索过滤器后显示未定义的数据 - jquery showing undefined data after search filter on select option Export to Excel Pdf is not working in Datatable after select option filter in php ajax - Export to Excel Pdf is not working in Datatable after select option filter in php ajax Select 选项基于 ajax 附带的数据 - Select option based on data that comes with ajax 想要在 select 选项中附加 Ajax 响应数据 - Want to apend Ajax response data in select option 使用对象选择选项通过Ajax请求加载数据时选择选项的问题 - Problems with selecting option with loading data with Ajax request with the object select option ajax请求后如何在html输入中自动选择“选择”选项? - How to auto select "select" option in html input after ajax request? select2 加载数据使用 ajax 不能 select 任何选项 - select2 load data using ajax cannot select any option 在jsp中的jQuery即时过滤器单击后单击html选择不更改选项 - Html select not changes option on click after jquery instant filter in jsp jQuery:排序后保留默认选择 <option>在<select>过滤 - jQuery: retain default selection after sorting <option>s in <select> filter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM