我在index.php页面上有一个搜索栏。但我想在coupons.php上显示结果。如何在AJAX中做到这一点。

注意:#search_result是coupons.php文件的div,我要在其中显示结果。

AJAX

$("document").ready(function() {
            $("#search_form").on("submit", function (e) {
                e.preventDefault();
                $.post("result.php?query=" + encodeURIComponent($("#list_search").val()), function (data) {
                    var res = JSON.parse(data);
                    if (res.divs) {
                         $('#search_result').html("");
                        for (var i = 0; i < res.divs.length; i++) {
                            $('#search_result').append(res.divs[i]);
                       }
                    } else {
                        $('#search_result').html("No matched coupons found !");
                    }
                });
            });
        });
    </script>

最佳答案

我假设您需要以某种方式在另一页上显示结果,但是不能使用服务器端。我不知道为什么要这么做,但是ajax肯定不是这种选择,如果您不能使用服务器端,则可以这样做。而不是在coupons.php页面上发送JSON响应。将搜索查询发送到优惠券页面。因此,您应该在index.php中创建一个类似这样的搜索表单

<form action="coupons.php" method="GET">
    <input type="text" name="query" />
    <input type="submit" value="Submit" />
</form>


然后,在coupons.php页面中,您可以通过window.location.search访问搜索查询,这将为您提供查询用户在

现在使用此查询,在coupons.php页面上,您将编写逻辑以获取json响应并将结果打印在#search_result元素中。

因此,您的coupons.php看起来像

$("document").ready(function() {
            var q = window.location.search; // q is your query string you got from index.php

                $.post('result.php'+q, function (data) {
                    var res = JSON.parse(data);
                    if (res.divs) {
                         $('#search_result').html("");
                        for (var i = 0; i < res.divs.length; i++) {
                            $('#search_result').append(res.divs[i]);
                       }
                    } else {
                        $('#search_result').html("No matched coupons found !");
                    }
                });
            });

10-08 08:40
查看更多