繁体   English   中英

无法使用asp.net c中的ajax jquery获取数据表单函数#

[英]can not get data form function using ajax jquery in asp.net c#

我正在尝试在asp.net中使用$ .ajax()方法填充html标签,但我没有从成功参数获取任何数据我从c#代码调用getData函数,我试图返回一个字符串,但它没有'工作我也尝试用户Response.write(),但同样的问题,当我提醒返回值它显示我的aspx页面代码如下图

警报数据图像

这是我的代码Default.apsx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" 
 %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>

        $(document).ready(function () {



            $("#firstDrop").on("change", function () {
                $.ajax({
                    url: "Default.aspx/getData",
                    type: "POST",
                    data: { id: $("#firstDrop").val() },
                    success: function (data) {
                        alert(data);
                        $("#secondDrop").html(data);
                    }
                });
            });

        });


    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <select runat="server" id="firstDrop">

        <option value="0">first select</option><option value="1">second select</option><option value="3">third select</option>

    </select>
        <select id="secondDrop"></select>
    </div>
    </form>
</body>
</html>

Default.aspx.cs

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }


    public  string getData()
    {
        return"<option>ABC</option><option>CDE</option>";
    }
}

在asp.net中创建web方法时的基本规则。

  • 你的方法应该是静态的。
  • 您需要使用System.Web.Services.WebMethod来装饰您的函数。

C#代码背后

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}

Javascript(Aspx)

在此输入图像描述

在这种情况下,在你的情况下,你的getdata函数也是静态的,webmethod也是如此。 通过ajax调用webmethod时,使用data.d来读取响应。

[System.Web.Services.WebMethod]
public static string getData(int id)
{
    return "<option>ABC</option><option>CDE</option>";
}

$("#firstDrop").on("change", function() {
    $.ajax({
        url: "Default.aspx/getData",
        type: "POST",
        dataType: "json",
        data: {
            id: $("#firstDrop").val()
        },
        success: function(data) {
            alert(data.d);
            $("#secondDrop").html(data.d);
        }
    });
});

参考站点:

https://www.aspsnippets.com/Articles/Calling-ASPNet-WebMethod-using-jQuery-AJAX.aspx

类似的主题“在webform中调用webmethod”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM