2012-02-20 56 views
0

我在学C#& ASP.NET做一个网站。我试图通过AJAX &访问.aspx脚本,只是返回一些HTML。C#代码:这是如何ASP.NET AJAX脚本工作?

所以我访问脚本http://www.mywebsite.com/test.aspx?i=199 &所有返回是:

<p>You queried: 199</p> 

ASP.NET是否允许我通过CGI变量(I = 199)还是我的意思使用不同的方法?

这是你的意思在ASP.NET网站使用脚本的正确方法:

Test.aspx文件:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="WebApplication1.test" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<div id="testDiv" runat="server"></div> 

<!-- Must I have the html, head & body elements or can I just return a div? --> 

test.aspx.cs:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace WebApplication1 
{ 
    public partial class test : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      int index = url.Split("i=").Last(); // this causes an error: split has some invalid arguments 
      testDiv.InnerHtml = string.Format("<p>You Queried: {0}", index); 
     } 
    } 
} 

我使用脚本的方式是在我的主页上有一个按钮,当点击发出一个AJAX请求到test.aspx & g回到p HTML元素/文本:

function getData(n) 
{ 
    $.ajax({ 
     type: "POST", 
     url: "test.aspx", 
     data: "i="+n 
     }).done(function(msg) { 
      $("textarea:first").html(msg)); 
     }); 
} 

<button onclick="getData(199)"/> 
+0

仅供参考,这不是一个CGI变量。这只是一个查询字符串。 – 2012-02-20 02:22:59

回答

1

这不是特定于asp.net。

您需要查看request object,特别是Query String集合。这些概念对许多Web服务器端语言/框架都很常见。通过个人经验,我用它在经典的asp,asp.net和php。

从查询字符串获取的价值:

string val = Request.QueryString["i"]; 
1
  1. 你不需要HTML,头部和身体的元素在这里。它们全部自动生成ASP.NET

  2. 您可以使用Request.QueryString("i")。您不需要手动分析Url。

  3. 到目前为止好,但我不明白<button onclick="getData(199)"/>

这是哪里的代码写的? ASP.NET服务器端控件onclick方法需要C#实现。如果你想定义客户端脚本,使用onclientclick

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclick.aspx