重定向页面后的Ajax调用

时间:2018-09-04 11:31:11

标签: jquery

他们是一种使用javascript重定向页面,然后直接进行ajax调用以将数据添加到该页面的方法:

以下操作无效( #application_search_result是重定向网址页面中的标记):

function searchApplication(element, event){
    //URL
    var redirectUrl = '/feeds/application_search.php';
    var url = '/feeds/lib/auto_suggest_application_search.php';

    //Redirect page 
    window.location = redirectUrl;

    //Ajax call
    $.ajax({
        url: url, 
        data: {
            "search": element.value.trim().replace(/ /g,"+")
        },
        success: function(result){
            $("#application_search_result").html(result);                    
        }
    }); 
}

1 个答案:

答案 0 :(得分:1)

对我来说,您是否想先搜索某些内容然后在页面中显示搜索结果?如果是这样,您可以执行与隐藏的Submit Form相同的操作,并将结果作为Json传递到PHP文件:

这是我的搜索功能:

function search(term) {
    if (term !== "" && term !== null && term !== "undefined") {
        swal({
            title: 'Search for ' + term,
            onOpen: function() {
                swal.showLoading();

                ... some code from me

                $.when(ajaxCall('search', params)).done(function(searchresult) {
                    setTimeout(function() {
                        swal.close();

                        if (searchresult) {
                            searchPOSTcall(searchresult);
                        } else {
                            swal({
                                type: 'error',
                                title: 'Nothing found!',
                            })
                        }
                    }, 500);
                });
            },
        })
    }
}

如您所见,我对搜索函数进行了Ajax调用,它返回了搜索结果。如果我得到一些结果,则将它们传递给“伪造”表单提交的重要功能:

function searchPOSTcall(params) {
        var form = document.createElement("form");
        form.setAttribute("method", "post");
        form.setAttribute("action", "/forecast");

        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", "searchresult");
        hiddenField.setAttribute("value", JSON.stringify(params));

        form.appendChild(hiddenField);
        document.body.appendChild(form);
        form.submit();
    }

请务必对搜索结果进行JSON.stringify,以避免出现很多错误。 然后在您的Results.php文件中,您可以得到如下结果:

<?php
    if(isset($_POST['searchresult'])) {
        $result = json_decode($_POST['searchresult']);
        ... do something with your results
    }
?>

希望这将帮助您解决问题。

编辑:

如评论中所述,您可以使用onLoad之类的东西在result.php中进行ajax调用。仅当您要先检查是否有任何搜索结果,然后将其传递到结果页面,以及如果找不到任何内容时,才使用我的方法。如果没有结果,这避免了不必要的重定向到结果页面。

相关问题