从javascript调用C#Web服务并使用它(json格式)

Call C# webservices from javascript and consume it (json format)

本文关键字:json 格式 调用 javascript C#Web 服务      更新时间:2023-09-26

我已经创建了一个c#webservice,我正在尝试从javascript脚本中调用它并使用它,什么是实现它的方法或最佳方法,提前感谢。我会解释更多:这是网络服务:

 public class DocumentInfo : System.Web.Services.WebService
{
    [WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
    public string GetDocumentInfo(string id)
    {
        Document document = new Document(Int32.Parse(id));    
        string output = JsonConvert.SerializeObject(document);
        return output;
    }
}

我已经测试过了,它是有效的,当我尝试建议的ajax解决方案时,我得到了这个错误500内部服务器错误。

阅读的一些教程

http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/http://weblogs.asp.net/jalpeshpvadgama/archive/2010/08/29/calling-an-asp-net-web-service-from-jquery.aspx

function TestService() 
{              
    try 
      {
       $.ajax({
         type: "POST",
         url: "http://webserviceURL.asmx/YourWebMethodName",
         data: "{'abc':'" + 123 + "'}", // if ur method take parameters
         contentType: "application/json; charset=utf-8",
         success: SuccessTestService,
         dataType: "json",
         failure: ajaxCallFailed
      });
    }
    catch (e)
    {
        alert('failed to call web service. Error: ' + e);
    }
}
function SuccessTestService(responce) {
    alert(eval(responce.d));
}

function ajaxCallFailed(error) {
        alert('error: ' + error);
    }

您需要发出AJAX请求并等待回调来接收数据。

使用jQuery的一个非常简单的例子:

$.ajax({
  url: "/my_service.cs"
}).done(function(data) { 
  console.log("Received: ", data);
});

使用jQuery AJAX:

$.ajax({
  url: 'YourServiceURL',
  success: function(data) {
     alert('Web Service Called!');
  }
});

http://api.jquery.com/jQuery.ajax/

go through this demo project it will help you in multiple direction 

http://www.codeproject.com/Articles/21045/Different-methods-to-call-Web-Services-from-AJAX

通过使用javascript ajax方法,您可以实现

  $.ajax({
                        type: "POST",
                        url: ,//webservice url
                        data: , // if ur method take parameters
                        contentType: "application/json; charset=utf-8",
                        success:{},
                        dataType: "json",
                        failure: {}
                    });