javascript - 使用 JQuery 和 AJAX 从 Aspx 页面返回数据

标签 javascript asp.net ajax jquery

我有一个仅包含 HTML 按钮的 aspx 页面 (Sample.aspx)。在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;
}
<小时/>

Note: ASP.NET AJAX Page Methods must be decorated with [WebMethod] attribute and must be static, thus they cannot interact with controls on the page, because there is no page instance.

<小时/>

标记:

$(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);
        }  
    });
});

关于javascript - 使用 JQuery 和 AJAX 从 Aspx 页面返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20476827/

相关文章:

javascript - 使滚动条在移动浏览器中可见

javascript - Jquery点击功能不加载新内容

javascript - 首先按 bool 列然后按字符串列对数组进行排序

Javascript onscroll 事件未被调用

javascript - 使用 nightmarejs 单击图像

c# - 通过 OpenId Connect 身份验证传递查询字符串参数

asp.net - 我如何使用asp.net MVC4隐藏URL中的ID

javascript - 使用 AJAX 解析从 ASP 页面返回的 HTML 表并提取特定单元格

javascript - Ajax 成功消息不起作用

javascript - 将回调 onSuccess 返回值提升为 Caller Function 返回值