環境:VS2019 .net 4.0 framework
根據教材使用ScriptManager在JavaScript中呼叫Web service 時,失敗,現將程序和解決方法記錄如下:
1、定義Web Service
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;namespace AjaxTest1{ /// <summary> /// WebService1 的摘要說明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // 若要允許使用 ASP.NET AJAX 從腳本中呼叫此 Web 服務,請取消注釋以下行, [System.Web.Script.Services.ScriptService] public class WebService1 : System.Web.Services.WebService { [WebMethod] public int GetTotal(string s,int x,int y) { if (s == "+") { return x + y; } if (s== "-") { return x - y; } if (s == "*") { return x * y; } if (s == "/") { return x / y; } else { return 0; } } }}
2、定義JavaScript和.aspx頁面;
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="AjaxTest1.WebForm1" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>js呼叫WebService實作運算器</title> <script type="text/javascript" > function RefService() { //alert(document.getElementById("Text1").value); var num1 = document.getElementById("Text1").value; var num2 = document.getElementById("Text2").value; var num3 = document.getElementById("Select1").value; //alert(document.getElementById("Select1").value); WebService1.GetTotal(num3, num1, num2, GetResult); //alert(document.getElementById("Select1").value); } function GetResult(result) { document.getElementById("Text3").value =https://www.cnblogs.com/hiwuchong/p/ result; //alert(result); } </script></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="~/WebService1.asmx"/> </Services> </asp:ScriptManager> 請分別輸入用于計算的兩個整數:<br /><br /> <input id="Text1" type="text" /> <select id="Select1" name="D1"> <option value=https://www.cnblogs.com/hiwuchong/p/"+" selected="selected">+</option> <option value=https://www.cnblogs.com/hiwuchong/p/"-">-</option> <option value=https://www.cnblogs.com/hiwuchong/p/"*">*</option> <option value=https://www.cnblogs.com/hiwuchong/p/"/">/</option> </select> <input id="Text2" type="text" /> <input id="Button1" type="button" value=https://www.cnblogs.com/hiwuchong/p/"=" onclick="RefService()" style="height:21px;width:30px"/> <input id="Text3" type="text" /> </form></body></html>
整個專案的目錄如下:

3、運行程式,點擊“=”,卻沒有任何效果:

4、解決方法:
在腳本中打上斷點,發現程式是可以執行到14行的,執行到15行的時候,就執行不下去了

5、在呼叫WebService的腳本處,加上命名空間:

運行成功:

總結:可能是教材上的范例年代久遠,已經不適用與VS2019了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/2946.html
標籤:ASP.NET
