简体   繁体   English

jQuery Ajax无法调用Asmx Web服务

[英]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 我在一个端口localhost:5739上运行asmx服务,并试图从项目的其他端口或纯HTML + jquery调用该服务

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. 调用服务机架的JS代码与服务位于同一主机上。 Just put html file at your project root folder and try to run it from the directory listing while debug. 只需将html文件放在项目的根文件夹中,然后在调试时尝试从目录列表中运行它。 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 若要使用ASP.NET AJAX从脚本中调用此Web服务,请在asmx服务类上方包含以下行,例如

[System.Web.Script.Services.ScriptService] public class GetData : System.Web.Services.WebService { [System.Web.Script.Services.ScriptService]公共类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, 在web.config中的system.web下添加协议,如果无法查看配置,请单击链接,

https://pastebin.com/CbhjsXZj https://pastebin.com/CbhjsXZj

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

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

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