简体   繁体   中英

Unable to call asmx web service by jquery Ajax

i am running asmx service in one port localhost:5739 and trying to call the service from other port or plain html + jquery out of the project

but i am unable to access the web service

my webservice is

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

and my code to invoke webservice is

            $.ajax(
            {
                type: "POST",
                url: "http://localhost:5739/asmxservices/testservice.asmx/HelloWorld",
                data: '{ "text": "Kartheek"}',                    
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                error: OnError

            });

            function OnSuccess(data, status) {
                alert(data.d);

            };
            function OnError(msg) {
                alert('error = ' + msg.d);
            }

Your method needs to be static, like this:

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

It seems that your trouble caused by file placement. JS code calling your service shold be on the same host as your service. Just put html file at your project root folder and try to run it from the directory listing while debug. As sample: I test service calling file with path

http://localhost:51169/2.html

The following Steps solved my problem, hope it helps some one,

  1. To allow this Web Service to be called from script, using ASP.NET AJAX, include the following line above your asmx service class for example

[System.Web.Script.Services.ScriptService] public class GetData : System.Web.Services.WebService {

  1. Add protocols under system.web in web.config, please click on the link if you are not able to view configuration,

https://pastebin.com/CbhjsXZj

<system.web>
<webServices>
  <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
</webServices>

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