简体   繁体   中英

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). The response that comes back is not consistent, however, it consistently fires the "error" jQuery callback as opposed to the "success" call back. 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. I debugged the code, and the webservice does actually execute without any exceptions.

ASPX Code

//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. 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. Just returning a string, it would come back as {'d':'Keivan'} instead of {'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.

Update:

Using ASP.NET 2.0, you need to install the ASP.NET AJAX Extensions v1.0 . Additionally, make sure your web.config is configured for ASP.NET AJAX (most specifically the HttpHandlers section).

This question will most likely help you.

Otherwise, I converted this web service to a page method and it worked immediately. Do you have that option?

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:

<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.

you say it's json, but it returns 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.

Try marking up your web method with [ScriptMethod]

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 ?

Curiously, he did NOT have the [Script Service] and the [WebMethod] in his download code.

Anyway, the aJax 500 12030 12031 errors are gone after the above changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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