【问题标题】:Requesting data from asp.cs thorugh ajax not working properly?通过 ajax 从 asp.cs 请求数据不能正常工作?
【发布时间】:2019-11-25 07:41:14
【问题描述】:

我现在正在学习 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;
        }

    }

webform1.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>

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

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

【问题讨论】:

  • alert("in success "+response); 在您的成功函数中查看您的 json 数据从服务器获取。也尝试发布它
  • 您是否收到警告中的用户名?或收到警报错误?有用的提示:将成功或错误附加到您的警报消息中。现在你不知道警报是来自成功还是失败。
  • @Swati 我尝试了你所说的,但窗口中没有弹出警报。我没有收到任何类型的成功/失败警报/
  • 检查你的浏览器控制台有没有错误?
  • 感谢您的帮助,我解决了这个问题。问题是 c# webmethod 应该是静态的,我错过了。

标签: jquery asp.net ajax webforms


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您必须将您的方法定义为静态方法,例如 ex。

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

    ajax 使用它。

    【讨论】:

      猜你喜欢
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 2012-06-16
      • 1970-01-01
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多