简体   繁体   English

使用jQuery AJAX与asp.net webservices总是会出错:而不是成功:

[英]using jQuery AJAX with asp.net webservices always goes to error: instead of success:

Issue 问题

I have an aspx page with jQuery code to send an ajax request over to an asmx web service file (on the same website). 我有一个带有jQuery代码的aspx页面,可以将ajax请求发送到asmx web服务文件(在同一个网站上)。 The response that comes back is not consistent, however, it consistently fires the "error" jQuery callback as opposed to the "success" call back. 返回的响应并不一致,但它始终触发“错误”jQuery回调而不是“成功”回调。 The status code inconsistently varies between 200, 12030, and 12031. The responseText of the message to the callback inconsistently varies between [blank] and the actual XML that the json webservice returns. 状态代码不一致地在200,12030和12031之间变化。对回调的消息的responseText在[blank]和json webservice返回的实际XML之间不一致地变化。 I debugged the code, and the webservice does actually execute without any exceptions. 我调试了代码,并且webservice确实执行而没有任何异常。

ASPX Code ASPX代码

//Code omitted for brevity //为简洁起见省略了代码

<script type="text/javascript">
jQuery(document).ready(function()
{
  jQuery.ajax({
  type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "CallDequeue.asmx/Dequeue",
    data: "{}",
    dataType: "json",
    success: function(Msg)
    {
      alert('success:' + Msg.responseText);
    },
    error: function(Msg)
    {
      alert('failed:' + Msg.status + ':' + Msg.responseText);
    }
  });
});
</script>

//Code ommitted for brevity //为简洁起见,省略了代码

Web Service Code 网络服务代码

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class CallDequeue : System.Web.Services.WebService
{
  [WebMethod]
  public string Dequeue()
  {
    return "{\"d\":{\"FirstName\":\"Keivan\"}}";
  }
}

When you mark the service as a ScriptService, it automatically handles the JSON serialization. 将服务标记为ScriptService时,它会自动处理JSON序列化。 You shouldn't manually serialize the response. 您不应手动序列化响应。

If you want the return to come back as "FirstName", then you can use a DTO class to control the syntax. 如果您希望返回“返回”作为“FirstName”,则可以使用DTO类来控制语法。 Just returning a string, it would come back as {'d':'Keivan'} instead of {'d':{'FirstName':'Keivan'}}. 只需返回一个字符串,它就会以{'d':'Keivan'}而不是{'d':{'FirstName':'Keivan'}}返回。

[ScriptService]
public class CallDequeue : System.Web.Services.WebService
{
  public class PersonDTO
  {
    public string FirstName;
  }

  [WebMethod]
  public PersonDTO Dequeue()
  {
    var p = new PersonDTO();

    p.FirstName = "Keivan";

    return p;
  }
}

A few changes to the calling syntax: 调用语法的一些更改:

jQuery(document).ready(function() {
  jQuery.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "CallDequeue.asmx/Dequeue",
    data: "{}",
    dataType: "json",
    success: function(Msg) {
      // Unless you're using 2.0, the data comes back wrapped
      //  in a .d object.
      //
      // This would just be Msg.d if you return a string instead
      //  of the DTO.
      alert('success:' + Msg.d.FirstName);
    },
    error: function(Msg) {
      alert('failed:' + Msg.status + ':' + Msg.responseText);
    }
  });
});

You can read more about ASP.NET AJAX's .d wrapper here , if you're interested. 如果您有兴趣,可以在这里阅读有关ASP.NET AJAX的.d包装器的更多信息

Update: 更新:

Using ASP.NET 2.0, you need to install the ASP.NET AJAX Extensions v1.0 . 使用ASP.NET 2.0,您需要安装ASP.NET AJAX Extensions v1.0 Additionally, make sure your web.config is configured for ASP.NET AJAX (most specifically the HttpHandlers section). 此外,请确保为ASP.NET AJAX (最具体地说是HttpHandlers部分) 配置了web.config

This question will most likely help you. 这个问题很可能会对你有所帮助。

Otherwise, I converted this web service to a page method and it worked immediately. 否则,我将此Web服务转换为页面方法,它立即起作用。 Do you have that option? 你有那个选择吗?

CS: CS:

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static string Dequeue()
    {
        return "{\"d\":{\"FirstName\":\"Keivan\"}}";
    }
}

ASPX: ASPX:

<script type="text/javascript">
    jQuery(document).ready(function()
    {
            jQuery.ajax({
            type: "POST",
              contentType: "application/json; charset=utf-8",
              url: "test.aspx/Dequeue",
              data: "{}",
              dataType: "json",
              success: function(Msg)
              {
                    alert('success:' + Msg.responseText);
              },
              error: function(Msg)
              {
                    alert('failed:' + Msg.status + ':' + Msg.responseText);
              }
            });     
    });

Check this and other Encosia articles out for more information. 有关更多信息,请查看文章和其他Encosia文章。

you say it's json, but it returns xml. 你说它是json,但它返回xml。 i see a slight disconnect there. 我看到那里有轻微的脱节。

Such a simple answer. 这么简单的答案。 My web.config wasn't ajax enabled so all calls (regardless of my webservice being a scriptservice) were returning XML instead of pure json. 我的web.config没有启用ajax,因此所有调用(无论我的webservice是一个脚本服务)都返回XML而不是纯json。

Try marking up your web method with [ScriptMethod] 尝试使用[ScriptMethod]标记您的Web方法

As in: 如:

[WebMethod]
[ScriptMethod]

My thanks to all the responders here. 我要感谢所有响应者。

Be sure to add these attributes in front of the methods to be used 请务必在要使用的方法前添加这些属性

[WebMethod] 
[ScriptMethod] 

Not sure when the ScriptMethod is needed ? 不确定何时需要ScriptMethod?

Curiously, he did NOT have the [Script Service] and the [WebMethod] in his download code. 奇怪的是,他的下载代码中没有[Script Service][WebMethod]

Anyway, the aJax 500 12030 12031 errors are gone after the above changes. 无论如何,在上述变化之后,aJax 500 12030 12031错误消失了。

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

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