简体   繁体   English

使用jquery调用ac#webservice

[英]Invoking a c# webservice using jquery

I am trying to create a webservice that takes data, posts it to a database, and returns the result. 我正在尝试创建一个Web服务,它接收数据,将其发布到数据库,并返回结果。 I know how to write all the C# code that does that, but it is the communication that I am having problems with. 我知道如何编写所有这样做的C#代码,但这是我遇到问题的沟通。 At the moment, I am just trying to invoke the service and get back "Hello World" (I start with something simple since I have no idea what I'm doing)... 目前,我只是试图调用该服务并返回“Hello World”(我从简单的事情开始,因为我不知道我在做什么)...

My Jquery: 我的Jquery:

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "PersonService.asmx/HelloWorld",
  data: "{}",
  dataType: "json",
  success: function(msg) {
    alert("Success");
    $("#log").html(msg);
    alert(msg);
  }
});

My Webservice: 我的网络服务:

public class PersonService : System.Web.Services.WebService
{
~

    [WebMethod(CacheDuration = CacheHelloWorldTime,
    Description="As simple as it gets - the ubiquitous Hello World.")]
    public string HelloWorld()
    {
        return "Hello World";
    }
~
}

After using chrome to Inspect the Element, and selecting the Network tab, finding my webservice, it shows me that the result was: 使用chrome检查Element后,选择Network选项卡,找到我的webservice,它显示结果是:

<?xml version="1.0" encoding="utf-8"?>
<string>Hello World</string>

So, it seems that the service executed successfully, but the success function does not fire, and there are no errors in the console. 因此,似乎服务执行成功,但成功函数不会触发,并且控制台中没有错误。 What is going on? 到底是怎么回事? Also, why is the result in XML? 另外,为什么结果是XML?

Do I need to use Web Services, or could I just post the variables via AJAX to an ASPX page that would process it the same way it would a form submission? 我是否需要使用Web服务,或者我可以通过AJAX将变量发布到ASPX页面,该页面将以与表单提交相同的方式处理它?

Using jQuery to Consume ASP.NET JSON Web Services » Encosia 使用jQuery来使用ASP.NET JSON Web服务»Encosia

$(document).ready(function() {
  $.ajax({
    type: "POST",
    url: "RSSReader.asmx/GetRSSReader",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
      // Hide the fake progress indicator graphic.
      $('#RSSContent').removeClass('loading');

      // Insert the returned HTML into the <div>.
      $('#RSSContent').html(msg.d);
    }
  });
});

Also, you're missing [ScriptMethod] on your web service method and [ScriptService] on your service class. 此外,您在Web服务方法和服务类上的[ScriptService]上缺少[ScriptMethod]

[WebService]
[ScriptService]
public class PersonService : WebService
{
    [ScriptMethod]
    [WebMethod(CacheDuration = CacheHelloWorldTime,
    Description="As simple as it gets - the ubiquitous Hello World.")]
    public string HelloWorld()
    {
        return "Hello World";
    }
}

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

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