Page頁調用js,js訪問WebService方法,來實現資料的非同步呼叫。
建立Default.aspx,拖放ScriptManager控制項到頁面中。
如下:
<asp:ScriptManager runat="server" ID="script1" EnablePageMethods="true">
<Scripts>
<asp:ScriptReference Path="~/Js/JScript.js" />
</Scripts>
<Services>
<asp:ServiceReference Path="~/WebService.asmx" />
</Services>
</asp:ScriptManager>
<input type="button" value="Ajax Say Hello" id="btnGetAjax" onclick="return SayHello()" />
<span id="result" />
建立一個Js檔案,方法如下:
function SayHello() {
WebService.HelloWorld(completeAjax);
}
function completeAjax(result) {
document.getElementById("result").innerHTML = result;
}
建立一個WebService.asmx檔案,在App_Code中會有WebService.cs
在該類中聲明:using System.Web.Services;
using System.Web.Script.Services;
[ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World - Li";
}
}
OK了,運行一下吧。這一個非常簡單的樣本!
希望有我,對大家都有協助!