javascript - 在另一个页面上显示搜索数据 <div>

标签 javascript php jquery html ajax

我有一个搜索栏在 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 !");
                    }
                });
            });

关于javascript - 在另一个页面上显示搜索数据 <div>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44133965/

相关文章:

javascript - 触发点击具有多个类的元素

javascript - JSON 的多个输入字段

php日期重新排列到mysql我需要使用explode吗?

php - 在我的 CSS 和 JavaScript 文件中嵌入 PHP 代码的正确方法是什么?

jquery - 使用类的 jQuery 选择器加上另一个属性

javascript - 为什么AngularJs中的$http可以被视为对象和函数?

javascript - 模态在移动设备上的位置不正确

javascript - React/JS - onMouseOver 更改字体

javascript - jQuery 不支持 .has 在 IE8 中?什么是解决方法?

php - 我可以使用 PHP 从 .xls 文件中提取数据,在没有 MySQL 的情况下对数据进行排序和调用吗?