我正在开发一个网页,该网页使用javascript和ajax进行所有数据查询和前端工作,我正在尝试编写excel导出功能。看作是在javascript中执行此操作的唯一方法似乎是使用仅在IE中可用的ActiveXControl,我想将其作为Sub包含在我的网页后面的代码文件中。
这似乎是一个好主意,但每当我点击按钮时,页面都会回发,并且所有要导出的数据都将消失。如果我在我的asp:Button上包含OnClientClick="return false;"
,按钮不会回发,但Sub也不会执行。有没有办法在不必使用注册客户端脚本块的情况下实现我的目标?非常感谢任何帮助。
谢谢!
- 编辑 -
我在方法调用的$ .ajax上获得了404。这是相关的代码。
//server side
Partial Class Report
Inherits System.Web.UI.Page
<System.Web.Services.WebMethod()>
Public Sub toXL()
Response.Write("<br><br>Here<br><br>")
End Sub
End Class
//client side
function toExcel() {
$.ajax({
type: "POST",
url: "/report.aspx/toXL",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.error) {
alert(msg.error);
}
return false;
}
});
}
//button
<asp:Button ID="MyButton" runat="server" AutoPostBack="false" type="button" OnClientClick="toExcel(); return false;" />
答案 0 :(得分:2)
您可以将方法描述为WebMethod,并将其称为来自jquery ajax的Web服务。运行ajax调用后返回false。
<asp:button OnClientClick="DoAction();" id="myid" runat="server"/>
public partial class _Default : Page
{
[WebMethod]
public static string MyMethod()
{
.......
}
}
function DoAction(){
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if(msg.error){
//show error
}
return false;
}
});
}