Calling an asmx service using jquery ajax asp.net 4.0

I am trying to call an example asmx service using jquery, here is the jquery code

$.ajax({ type: "POST", url: "/Services/Tasks.asmx/HelloWorld", data: "{}", dataType: "json", contentType: "application/xml; charset=utf-8", success: function (data) { alert(data); } }); 

This message is not displayed, the code is in asp.net 4.0, am I missing something?

Edit - I changed dataType to xml, now the success function works, returning after xml

 <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/">Hello World</string> 

I use the following code to parse xml data and it shows null in alert

 success: function (data) { edata = $(data).find("string").html(); alert(data); } 
+7
source share
4 answers

I believe it because you have dataType: "json" and it expects the content type of the response to be the same, but XML is returned. I bet the full event rises, but fails.

try

 $.ajax({ type: "POST", url: "/Services/Tasks.asmx/HelloWorld", data: "{}", dataType: "json", contentType: "application/xml; charset=utf-8", success: function (data) { alert(data); }, complete: function (data) { alert(data); } }); 

UPDATE

I think because you are using .html (), you need to use text (). Also I do not know if you want to do this or not, but you have data in your warning, I assume that you wanted to use edata . The following worked for me:

 jQuery.ajax({ type: "POST", url: "/yourURL", dataType: "xml", data: "{}", contentType: "application/xml; charset=utf-8", success: function(data) { edata = $(data).find("string").text(); alert(edata); } }) 
+6
source

I would recommend adding the [ScriptService] attribute to your Tasks.asmx class so that it accepts and responds in JSON instead of XML. Your client code looks good, but you'll want to look at "data.d" instead of "data" in your success handler.

+2
source
  use it. <script> alert("aaa"); $.ajax({ type: "POST", url: "MyService.asmx/HelloWorld", data: "{}", dataType: "xml", contentType: "application/xml; charset=utf-8", success: function (data) { alert(data);//data-object xmldocument edata = $(data).children("string").text(); alert(edata); } }); alert("bbb"); </script> 
+2
source

Well, you state that dataType is JSON, but contentType is XML. Try

 contentType: "application/json; charset=utf-8", 

If not, then we will need to see the asmx code.

+1
source

All Articles