首页 > 解决方案 > ajax 调用后执行 javascript 重定向

问题描述

我正在尝试使用 ajax 解析要在 php 页面上处理的数据,并让 php echo 将 javascript 重定向到另一个页面,但它不起作用。我读过js在运行ajax调用后不起作用,所以我想知道是否有解决方法。这是我的代码:

html

<form>
    <div class="depart_time bottom_white w-40 ml-auto">
            <p>Time</p>
            <input type="time" name = "return_time" id = "rt">
    </div>
    <div class = "search_button r_search">
        <button id = "r_search" onclick = "return false" onmousedown = "rent()">SEARCH</button>
    </div>

</form>

ajax 调用是一个普通的 xhttp 请求,它被发送到 php 进行处理,之后应该发生重定向:

if(isset($_POST['return_time'])){
    echo '<script type="text/javascript">window.location.href="link.html"</script>';
}

请帮助表示赞赏。我是使用 ajax 的新手。

编辑 ajax 代码:

gid("r_search").addEventListener("mousedown", rent);
    function rent(){
        rt = gid('rt').value;
        r_search = gid('r_search').value;

        form_array = '&rt=' + rt +
        '&r_search=' + r_search;

        send_data = form_array;

        ajax_data('app/rent.php', 'error', send_data);
        //gid('error').innerHTML = send_data;
    }


function ajax_data(php_file, getId, send_data){
        gid(getId).innerHTML = "loading";
        var xhttpReq = new XMLHttpRequest();
        xhttpReq.open("POST", php_file, true);
        xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttpReq.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                gid(getId).innerHTML = xhttpReq.responseText;
            }
        };
        xhttpReq.send(send_data);
    }

请注意,'gid' 用于 getelementbyid

标签: javascriptphpajax

解决方案


您必须对重定向方式进行一些更改。

首先,您需要更改您的 PHP 响应

if(isset($_POST['return_time'])){
    ...

    // If you get your process success return 1
    if(success) { 
        echo 1; die(); 
    } else {
        // else set some flag that you could get on your AJAX response
        echo 0; die();
    }
}

现在,在您的 AJAX 上获取此标志并对以下函数进行更改:

function ajax_data(php_file, getId, send_data){
        gid(getId).innerHTML = "loading";
        var xhttpReq = new XMLHttpRequest();
        xhttpReq.open("POST", php_file, true);
        xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttpReq.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                if( xhttpReq.responseText == 1 ) window.location.href="URL where you wish to redirect page";
            }
        };
        xhttpReq.send(send_data);
    }

我已经为其他来这里寻求帮助的人写了这个答案。


推荐阅读