c# - 如何调用不带参数的c#方法并访问返回的数据?

标签 c# javascript jquery ajax json

所以我见过很多这样的例子: https://stackoverflow.com/a/8094230/2525507

public class WebService : System.Web.Services.WebService {
   [WebMethod]
   public List<string> getList() {
      return new List<string> {"I", "Like", "Stack", "Overflow"};
   }
}

您刚刚似乎通过成功函数可以以警报的形式查看从 c# 方法返回的数据。但是,如果我想在函数调用之外访问这个“input+1”数据,我将如何进行呢?另外我不确定如何调用没有参数的方法?

<body>

<select id="wordSelect">
// Drop Down Menu to be populated 
</select>

<script>
  $(function () {
    $.ajax({
      url: 'WebService.asmx/getList',
      data: '{**NO PARAMETERS?!**}', // should I also call JSON.stringify?
      type: 'POST',
      dataType: 'json',
      contentType: 'application/json',
      success: function (data, status) {
        alert(data);
        alert(typeof data);
      }
    });
  });

 $.each(data.i, function(index, item) { // will this access "I", "Like", ... etc?
     $(#wordSelect).append(
         $("<option></option>")
             .text(item)
     );
 };
</script>

</body>

最后,我想使用从通过 ajax 调用的 c# 方法返回的 JSON 数据填充下拉列表,但我不确定如何使用似乎卡住的检索到的 JSON 数据在函数调用中?

对不起,我是 Jquery/AJAX/等的新手...但是非常感谢!

最佳答案

如果你的方法没有参数,就不要在 ajax 调用中指定数据属性

<script>
  $(function () {
    $.ajax({
      url: 'WebService.asmx/getList',
      type: 'POST',
      dataType: 'json', //make sure your service is actually returning json here
      contentType: 'application/json',
      success: function (data, status) {
        //here data is whatever your WebService.asmx/getList returned
        //populate your dropdown here with your $.each w/e
      }
    });
  });
</script>

我也可能是错的,但是您展示的 WebService 方法看起来不会返回 json。我认为您必须序列化或设置内容类型或类似内容。 (自从我使用了 asmx 类型的服务以来已经有一段时间了)

关于c# - 如何调用不带参数的c#方法并访问返回的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24500744/

相关文章:

c# - 将数组传递给存储过程时,对象必须实现 IConvertible 错误

javascript - 无法动态使内容可编辑以在 Angular 2 中进行内联编辑

jquery - jquery中将字符串转换为int并删除字符串中的逗号

jquery - 加载 div 内的所有图像后执行函数

javascript - 循环遍历具有组合在一起的元素的 jQuery 对象

c# - 启动应用程序在注销和重新登录之前不会启动

c# - 调用SQL Server存储过程的问题

c# - 如何获取Azure中所有存储帐户的列表? (C#)

javascript - Jquery 闪烁的标题

javascript - Jquery live 不能在 IE 中运行