简体   繁体   English

用Ajax调用JavaScript函数

[英]Calling a javascript function with ajax

I'm using a multiselect dropdown to filter images stored in my db. 我正在使用多选下拉列表来筛选存储在数据库中的图像。 The results are paginated, however the pagination fails once the results are filtered. 对结果进行分页,但是一旦对结果进行过滤,分页就会失败。 The filter uss ajax to make a php call to the database. 过滤器使用ajax对数据库进行php调用。

What I think is happening is that the once the results are loaded in the div the paginate javascript function has already fired and wont a second time. 我认为正在发生的事情是,一旦将结果加载到div中,分页javascript函数就已经触发并且不会第二次出现。 Is there a way to call the function everytime the results are filtered? 有什么方法可以在每次过滤结果时调用该函数?

I believe I just need to recall this each time: 我相信我每次都只需要回忆一下:

    <script type="text/javascript">

jQuery(function($){

    $('ul#items').easyPaginate({
        step:6
    });

});    

    </script>

Ajax call: Ajax呼叫:

<script>
function filterResults(sel)
{
    var selectedOptions = [];
    for (var i = 0; i < sel.options.length; i++) {
        if (sel.options[i].selected) {
            selectedOptions.push("'" + sel.options[i].value + "'");
        }
    }
    if (selectedOptions.length == 0) {
        document.getElementById("divResults").innerHTML="";
        return;
    }
    str = selectedOptions.join(",");
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else  {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("divResults").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","filter_ajax.php?filter="+str,true);
    xmlhttp.send();
}

</script>

ajax_filter.php: ajax_filter.php:

<?php

    include ("connect.php");

    $filter = $_GET["filter"];
    $filterIn = $filter;

        $result = mysql_query("SELECT * FROM edt_images
                                WHERE category1 IN ($filterIn)
                                OR category2  IN ($filterIn)
                                OR category3  IN ($filterIn)
                                OR category4 IN ($filterIn)
                                OR category5 IN ($filterIn)
                                OR category6 IN ($filterIn)")                           
            or die(mysql_error());

        echo "<div id='results_container'>";
        echo "<ul id='items'>";

        while ($row = mysql_fetch_array($result)) {

            echo "<li><img src='files/300x200/thumb2_".$row['item_name'].".".$row['file_extension']."' class='filtered_images' border='0'/></li>"; 
        }
        echo "</ul>";
        echo "</div>";
?>

If you are using jQuery you can simplify the code within the filterResults function greatly by utilizing the framework it provides. 如果使用的是jQuery,则可以利用它提供的框架极大地简化filterResults函数中的代码。 I would read up a bit here as you will be amazed by the extensive functionality. 我会在这里阅读一些内容因为您会对强大的功能感到惊讶。

This code is the jQuery equivalent of your previous code, 此代码与您先前的代码等效于jQuery,

   function filterResults(sel) {
        var selectedOptions = [];
        for (var i = 0; i < sel.options.length; i++) {
            if (sel.options[i].selected) {
                selectedOptions.push("'" + sel.options[i].value + "'");
            }
        }
        if (selectedOptions.length == 0) {
            $("divResults").html("");
            return;
        }
        filteStr = selectedOptions.join(",");
        $.ajax({
            url: "http://www.google.com",
            type: "get",
            dataType: "html",
            data: {
                filter: filteStr
            },
            success: function (responseHtml) {
                $("divResults").html(responseHtml);
                //You can put your code here
                $('ul#items').easyPaginate({
                    step: 6
                });
            },
            error: function (responseHtml) {
                //Handle error
            }
        });
    }

To answer the question the code within the success callback of the ajax call will be executed upon a receiving the data back from the server. 为了回答这个问题,ajax调用的success回调中的代码将在从服务器接收回数据后执行。 This code above should work as expected. 上面的代码应按预期工作。

Almost everything to know lies here and here . 几乎所有要了解的东西都在这里这里 ;) ;)

Well

According to the comments I'll have to study up on javascript and jquery, never really was to concerned with it before. 根据评论,我将不得不学习javascript和jquery,以前从未真正关心它。

Anyways by recalling the javascript function 无论如何,通过调用javascript函数

if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("divResults").innerHTML=xmlhttp.responseText;
            RESTATING HERE
}

I was able to get it working. 我能够使它工作。

Put javascript call into your php-ajax echo, example: 将javascript调用放入您的php-ajax回显中,例如:

<?
$msg = "hello";
?>
<script type="text/javascript">alert("<?=$msg?>"></script>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM