从asp请求数据.cs ajax无法正常工作



我正在学习 asp.net 到目前为止,我正在尝试访问服务器数据并将数据分配给文本框。

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

        }
        [WebMethod]
        public string GetStringValue()
        {
            return Environment.UserName;
        }
    }

网络表单1.aspx.cs :

<div class="form-group">
    <div class='col-sm-3'>
      <label >Username</label>
      <input id="username"  class="form-control input-sm" >
    </div>
    </div>
   <script type="text/javascript">
             $(document).ready(function () {
                 function getEmployees() {
                     $.ajax({
                         type: "POST",
                         url: 'WebForm1.aspx/GetStringValue',
                         contentType: "application/json; charset=utf-8",
                         dataType: "json",
                         success: function (response) {
                             alert(response);
//I want to assign the response value into username textbox while the form is loaded
                         },
                         failure: function (response) {
                             alert(response);
                         }
                     });
                 }
             });
        </script>

我希望将环境用户名值粘贴到文本框中。我对网络开发非常基本。

问题是我无法在开发人员工具中追踪原因。

你需要写一些东西来在页面加载时调用方法

         $(document).ready(function () {
                 $.ajax({
                     type: "POST",
                     url: 'WebForm1.aspx/GetStringValue',
                     contentType: "application/json; charset=utf-8",
                     dataType: "json",
                     success: function (response) {
                         $('#username').val(response);
                     },
                     failure: function (response) {
                         alert(response);
                     }
                 });
         });

你必须将你的方法定义为静态的,就像 ex 一样。

[WebMethod]
    public static  string GetStringValue()
    {
        return Environment.UserName;
    }

Ajax与它一起工作。

最新更新