response.write输出 改变页面的结构

本文详细介绍了在ASP.NET页面中使用RegisterClientScriptBlock和RegisterStartupScript方法来解决Response.Write导致的页面结构混乱问题。通过比较不同方法在页面输出位置的区别,提供了有效的解决方案,确保了页面的正常显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用response.write输出东西了。输出的东西在页面的最上面,比如
....
<Doctype ...>
<html> ..
也就是在页面的前面加了东西,这样就破坏了页面的结构,感觉上,css也就出问题了。呵呵
事实上是response.write打乱了页面的结构所致,解决方案如下:
方法0:换成客户端脚本程序

Page.RegisterStartupScript("ssss", "<script>alert('图片格式不正确')</script>");

说明:ssss相当一个标识ID,只要不重覆就可以

方法一:把 Response.Write()语句替换为这个
Page.RegisterStartupScript("ServiceManHistoryButtonClick", "<script>window.open('EquipmentHistory.aspx?eid=" + ServiceManDropDownList.SelectedValue + "');</script>");
这个方法用于在页响应中发出客户端脚本块,前一个参数是该Script在页面中的唯一名称(随便起,不重复就行),后一个是脚本内容。
这个方法应该是微软官方推荐的方法。

方法二:在原程序的Response.Write()语句后再加一句
Response.Write("<script>document.location=document.location;</script>");
 
 
 
======================================================================

解决:使用RegisterClientScriptBlock或RegisterStartupScript方法。

namespace Common
{
    /// <summary>
    /// 提示信息
    /// </summary>
    public class MessageBox
    {
        public static void Alert(Page page,string message)
        {
            if (!page.ClientScript.IsClientScriptBlockRegistered("demo"))
            {
        //HttpContext.Current.Response.Write("<script>document.location=document.location;alert('" +message + "');</script>");网上有人使用这种解决方法,但重设document.location会重新加载页面。
                  page.ClientScript.RegisterClientScriptBlock(page.GetType(), "demo", "<script>alert('" + message +"');</script>");
            }
        }
    }
}

使用:

Common.MessageBox.Alert(this,"每位学生只能选择一个题目!");

DEMO,查看几种方法输出的位置区别:

后台文件,Default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Response.Write("<script>alert('Hello'');</script>");

        //this.ClientScript.RegisterStartupScript(this.GetType(), "demo", "<script>alert('" + "Hello" + "');</script>");
        this.ClientScript.RegisterClientScriptBlock(this.GetType(), "demo", "<script>alert('Hello'');</script>");
    }
}

输出的页面:

Response.Write输出在页面内容上方。

<script>alert('Hello');</script>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title></head>
<body>
    <form name="form1" method="post" action="Default.aspx" id="form1">
    <div>
      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"   

        value="/wEPDwULLTE2MTY2ODcyMjlkZAVpRcHibkbkAXYhTouZnL6SNJ8d" />
    </div>

      <div>

      </div>
    </form>
</body>
</html>

RegisterStartupScript输出在ASP.NET页面底部,关闭元素</form>之前。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title></head>
<body>
  <form name="form1" method="post" action="Default.aspx" id="form1">
    <div>
      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"

        value="/wEPDwULLTE2MTY2ODcyMjlkZAVpRcHibkbkAXYhTouZnL6SNJ8d" />
    </div>

      <div>
      </div>
    <script>alert('Hello');</script>

  </form>
</body>
</html>

RegisterClientScriptBlock输出在ASP.NET页面中开启元素<form>之后。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title></head>
<body>
    <form name="form1" method="post" action="Default.aspx" id="form1">
    <div>
      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"

        value="/wEPDwULLTE2MTY2ODcyMjlkZAVpRcHibkbkAXYhTouZnL6SNJ8d" />
    </div>

    <script>alert('Hello');</script>
      <div>
      </div>
    </form>
</body>
</html>


如何将其与以下后端代码相匹配,即不改变后端代码的前提下,使得http页面的抽卡结果在后端生成,http页面的其他功能跟之前一样。以下为后端代码(s代表5星,a代表4星,b代表三星):package com.Controller; import com.entity.User; import com.jdbc.UserDao; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.sql.Timestamp; @WebServlet("/recordCardDraw") public class RecordCardController extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); String cardResult; if (user != null) { UserDao userDao = new UserDao(); User refreshedUser = userDao.queryUserById(user.getId()); int drawingTimes = refreshedUser.getDrawingtimes(); // 判断是否触发保底 if (drawingTimes >= 19) { int b = (int) (Math.random() * 1000); if(b<500){ cardResult = "S1"; } else { cardResult = "S2"; } } else { // 正常抽卡逻辑:随机生成结果 int a = (int) (Math.random() * 1000); if(a<25){cardResult = "S1";} else if(a<50){cardResult = "S2";} else if(a<80){cardResult = "A1";} else if(a<110){cardResult = "A2";} else if(a<140){cardResult = "A3";} else if(a<160){cardResult = "A4";} else if(a<200){cardResult = "A5";} else if(a<360){cardResult = "B1";} else if(a<520){cardResult = "B2";} else if(a<680){cardResult = "B3";} else if(a<840){cardResult = "B4";} else {cardResult = "B5";} } // 更新抽卡次数 userDao.updateDrawingTimes(user.getId()); // 抽到SSS就重置次数 if ("S1".equals(cardResult)||"S2".equals(cardResult)) { userDao.resetDrawingTimes(user.getId()); } //获取当前时间 Timestamp cardtime = new Timestamp(System.currentTimeMillis()); // 记录结果 userDao.recordCardDraw(user.getId(), cardResult, cardtime.toLocalDateTime()); // 返回抽卡结果给前端 response.setContentType("application/json"); response.getWriter().write("{\"status\":\"success\",\"cardResult\":\"" + cardResult + "\"}"); return; } // 如果用户未登录或错误 response.setContentType("application/json"); response.getWriter().write("{\"status\":\"error\"}"); } }
最新发布
07-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值