使用JQuery&异步传输

Returning data from Aspx page using JQuery & AJAX

本文关键字:异步传输 amp JQuery 使用      更新时间:2024-06-08

我有一个aspx页面(Sample.aspx),其中只包含一个HTML按钮。在aspx页面的.CS文件中,我编写了一个小函数(sample_function),它只返回一个字符串"Hello World"。当用户单击按钮时,我试图在"警报"框中显示该字符串。问题是,当我单击按钮时,.aspx页面的整个源代码都会显示在"警报"框中,而不是显示"Hello World"。请帮我解决这个问题。下面是我对Sample.aspx页面的总结代码。

<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#Button1").click(function () {
            $.post("Sample.aspx/sample_function",
    {
    },
    function (data, status) {
        alert("Data: " + data + "'nStatus: " + status);
    });
    });
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div >
    <input id="Button1" type="button" value="Click Me" /></div>
    </form>
</body>

下面是我的.cs代码的摘要版本:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication4
{
    public partial class Sample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        public string sample_function()
        {
            string s1 = "Hellow World";
            return s1;
        }
    }
}

使用ASP.NET AJAX页面方法,如下所示:

代码背后:

[WebMethod]
public static string sample_function()
{
    string s1 = "Hellow World";
    return s1;
}

注意:ASP.NET AJAX页面方法必须使用[WebMethod]属性进行修饰,并且必须是静态的,因此它们不能与页面上的控件交互,因为没有页面实例。


标记:

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "Sample.aspx/sample_function",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            alert(result.d);
        }  
    });
});

您必须有一个WebMethod。

[WebMethod]
public static string sample_function()
{
    string s1 = "Hellow World";
    return s1;
}