簡體   English   中英

jQuery Ajax無法調用Asmx Web服務

[英]Unable to call asmx web service by jquery Ajax

我在一個端口localhost:5739上運行asmx服務,並試圖從項目的其他端口或純HTML + jquery調用該服務

但我無法訪問網絡服務

我的網絡服務是

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

我調用網絡服務的代碼是

            $.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);
            }

您的方法必須是靜態的,如下所示:

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

看來您的麻煩是由文件放置引起的。 調用服務機架的JS代碼與服務位於同一主機上。 只需將html文件放在項目的根文件夾中,然后在調試時嘗試從目錄列表中運行它。 作為示例:我測試帶有路徑的服務調用文件

http://localhost:51169/2.html

以下步驟解決了我的問題,希望對您有所幫助,

  1. 若要使用ASP.NET AJAX從腳本中調用此Web服務,請在asmx服務類上方包含以下行,例如

[System.Web.Script.Services.ScriptService]公共類GetData:System.Web.Services.WebService {

  1. 在web.config中的system.web下添加協議,如果無法查看配置,請單擊鏈接,

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