【问题标题】:Can't consume ASP.NET Web Service from jQuery无法从 jQuery 使用 ASP.NET Web 服务
【发布时间】:2010-12-29 21:30:51
【问题描述】:

这是一个有趣的问题:

我有一些看起来像这样的 jQuery:

$(document).ready(function() {
  $.ajax({
    type: "POST",
    url: "http://localhost:63056/Service1.asmx/PrintOrderRecieptXml",
    data: {
      "CouponCode": "TESTCODE",
      "Subtotal": 14.2600,
      "ShippingTotal": 7.5000,
      "TaxTotal": 0.0000,
      "GrandTotal": 21.7600,
      "OrderItemCollection": [{
        "Total": 14.2600,
        "Qty": 250
      }]
    },
    dataType: "json",
    contentType: "application/json",
    error: function(xhr, msg) {
      alert(xhr.statusText);
    }
  });
});

现在,我遇到的问题是它正在发送请求,但 Web 服务没有正确处理它。在 IE 中,我收到一个带有“内部服务器错误”的警告框,而在 FireFox 中,我收到一个里面没有任何内容的警告框。

奇怪的是,当我使用 IE 时,我的事件日志中没有出现错误事件,但是使用 firefox 我得到了(弄清楚为什么会这样):

“异常消息:无法识别请求格式,因为 URL 意外以 '/PrintOrderRecieptXml 结尾”

我浏览了一些,发现有时您必须添加:

<webServices>
  <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost" />
    <add name="HttpPostLocalhost"/>

  </protocols>
</webServices>

到您的 Web.Config,我这样做了,但没有帮助。有趣的是,Web 服务可以与 SOAP 或发送查询字符串一起正常工作,但不能与 JSON 一起工作。

有什么想法吗?

【问题讨论】:

    标签: asp.net jquery web-services json


    【解决方案1】:

    您需要将您的输入作为 JSON 字符串而不是对象提供给 data 属性:

    $(document).ready(function() {
      $.ajax({
        type: "POST",
        url: "http://localhost:63056/Service1.asmx/PrintOrderRecieptXml",
        data: '{"CouponCode":"TESTCODE","Subtotal":14.2600,"ShippingTotal":7.5000,"TaxTotal":0.0000,"GrandTotal":21.7600,"OrderItemCollection":[{"Total":14.2600,"Qty":250}]}',
        dataType: "json",
        contentType: "application/json",
        error: function(xhr, msg) {
          alert(xhr.statusText);
        }
      });
    });
    

    Using jQuery to Consume ASP.NET JSON Web Services 很好地解释了与 ASP.Net Web 服务对话时的要求。

    【讨论】:

    • 这似乎是正确的道路。但是,在Firefox中仍然不起作用。在 IE 中运行良好。
    • 现在如何在 Firefox 中失败?您在服务器上看到请求了吗? ASP.Net 是否正确处理了请求?它是否击中了您的 error 处理程序客户端?
    • 我也有同样的问题,响应返回到 ajax 调用的成功函数,但响应对象本身在 Firefox 中始终为空。
    【解决方案2】:

    Douglas 是正确的 - 您需要将数据格式化为字符串。请务必阅读他链接到您的博客上的所有帖子。 Encosia 是 Ajax 和 Asp.Net 的绝佳资源。

    【讨论】:

      【解决方案3】:

      asp.net webservices 不能正常返回json。看看这里: JSON WebService in ASP.NET

      【讨论】:

        猜你喜欢
        • 2013-04-08
        • 2011-03-31
        • 1970-01-01
        • 1970-01-01
        • 2017-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多