【问题标题】:Call web service using json使用 json 调用 web 服务
【发布时间】:2014-01-18 18:29:41
【问题描述】:

我有两个项目:

ASP.net 网站项目:

默认.aspx

     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type = "text/javascript">

   function DisplayMessageCall() {
    $.ajax({
        type: "POST",
        url: "http://localhost:24218/Service1.asmx/HelloWorld",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccessCall,
        error: OnErrorCall
    });
}
function OnSuccessCall(response) {
    $('#<%=lblOutput.ClientID%>').html(response.d);
}

function OnErrorCall(response) {
    alert(response.status + " " + response.statusText);
}

 </script>

  <h2>Example 1: Call Webservice using JQuery AJax (Without Input)</h2>

<asp:Button ID="btnGetMsg" runat="server" Text="Click Me" OnClientClick="DisplayMessageCall();return false;" /><br />

<asp:Label ID="lblOutput" runat="server" Text=""></asp:Label>

和 ASP Web 服务应用程序:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string HelloWorld()
    {
        return "Hello World";
    }
}

我在我的 ASP 网站中添加了我的 webService 的引用,但是当我单击按钮时,我收到了错误消息。 当我输入网址时

                  (http://localhost:24218/Service1.asmx/HelloWorld) 

在浏览器中我得到以下结果:

          <string xmlns="http://tempuri.org/">Hello World</string>

我使用 ASP.NET 4.5。

【问题讨论】:

  • ASMX 是一项遗留技术,不应用于新开发。 WCF 或 ASP.NET Web API 应该用于 Web 服务客户端和服务器的所有新开发。一个提示:Microsoft 已停用 MSDN 上的 ASMX Forum

标签: c# asp.net json asmx service-reference


【解决方案1】:

看起来您配置了 GET 方法而不是 POST 方法。如果您将 $ajax 调用切换为:

   $.ajax({
      type: "GET",
      . . .

那么它可能会起作用

【讨论】:

  • 在哪里配置GET或POST方法不起作用?
  • 点击网址时得到XML结果是否正常:tempuri.org/">HelloWorld ?
  • 是的,这很正常。你需要 [WebMethod] [ScriptMethod(UseHttpGet=true)] (见stackoverflow.com/a/10752837/275501
  • 我添加了 [WebMethod][ScriptMethod(UseHttpGet=true)] 如果我的 Web 服务位于我的网站中,它就可以正常工作,但是当我调用位于另一个 Web 服务项目中的 Web 服务时不起作用。添加服务参考后我错过了什么吗??
  • 如果您从 javascript 调用它,则根本不需要网络引用。当它位于另一个 Web 服务项目中时,您会遇到什么错误?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
  • 2012-04-15
相关资源
最近更新 更多