响应.重定向和javascript ajax调用

Response.Redirect and javascript ajax call

本文关键字:ajax 调用 javascript 重定向 响应      更新时间:2023-09-26

我正在使用javascript对服务器进行调用。javascript代码如下,

function cs() {
    alert("");
    var xmlhttp;
    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("myDiv").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", "lp.aspx?pb=true", true);
    xmlhttp.send();
}

我的服务器代码遵循

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.QueryString["pb"] != null) 
    {
        Response.Redirect("main.aspx");
    }
}

问题出在我的响应上。Redirect无法处理我的ajax调用。为什么?

您不能在ajax调用上重定向,因为它需要从调用的页面返回一些值。若该页面本身重定向,它就无法告诉调用函数重定向,因为它只是希望在success回调中返回一些值。

所以为了解决这个问题,如果条件满足,您可以返回一个param,比如{ redirect: true }。在success回调中,如果redirect为true,则使用JS-window.location.href="required"重定向。

我认为重定向不起作用,因为带有javascript的页面的响应在AJAX调用之前就已经关闭了。

不使用Response.RRedirect,您可以发回一个包含url的字符串,并在脚本中使用location.href进行重定向。

很简单,您不能在ajax调用上使用响应。使用

window.location