日前做到一个需求.net后台获取js返回值,根据前台获取yes or no,后台执行不同业务逻辑。
解决方案:后台业务逻辑写入第三方页面,前台脚本使用JQ Ajax请求。
DEMO:点击按钮弹出Confirm,Sure加法运算,Cancel减法运算,运算逻辑写于第三方页面。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo_ReturnConfirm.aspx.cs" Inherits="ClientTest.Demo_ReturnConfirm" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="js/jquery-2.1.0.js"></script> <script type="text/javascript"> function operate() { var p_one = $("#txtOne").val(); var p_two = $("#txtTwo").val(); var a = confirm("点击确定加法运算,取消减法运算"); if (a == true) { $.ajax({ type: "Get", //访问WebService使用Post方式请求 url: "index.aspx", //调用WebService data: 'type=Add&p_one=' + p_one + '&p_two=' + p_two, dataType: 'html', // cache: false, //beforeSend: function (x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); }, error: function (x, e) { alert("Error:" + x + e) }, success: function (result) { //回调函数,result,返回值 alert(result); } }); } else { $.ajax({ type: "Get", //访问WebService使用Post方式请求 url: "index.aspx", //调用WebService data: 'type=Cut&p_one=' + p_one + '&p_two=' + p_two, dataType: 'html', //cache: false, //beforeSend: function (x) { x.setRequestHeader("Content-Type", "application/json; charset=utf-8"); }, error: function (x, e) { alert("Error:" + x + e) }, success: function (result) { //回调函数,result,返回值 alert(result); } }); } return false; }; </script> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="txtOne" runat="server"></asp:TextBox> <asp:TextBox ID="txtTwo" runat="server"></asp:TextBox> <asp:Button ID="BtnSure" runat="server" Text="Operate" OnClientClick=" return operate()" /> </div> </form> </body> </html>
public partial class Index : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["type"] == "Add" && Request.QueryString["p_one"] != null && Request.QueryString["p_two"] != null) { Response.Write(Operate_Add(Convert.ToInt32(Request.QueryString["p_one"].ToString()), Convert.ToInt32(Request.QueryString["p_two"].ToString()))); Response.End(); } if (Request.QueryString["type"] == "Cut" && Request.QueryString["p_one"] != null && Request.QueryString["p_two"] != null) { Response.Write(Operate_Cut(Convert.ToInt32(Request.QueryString["p_one"].ToString()), Convert.ToInt32(Request.QueryString["p_two"].ToString()))); Response.End(); } }
private string Operate_Add(int p_one, int p_two) { return (p_one + p_two).ToString(); } private string Operate_Cut(int p_one, int p_two) { return (p_one - p_two).ToString(); } }