html頁
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="js/Jquery1.7.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#txtUserName').blur(function () {
$.ajax({
type: "post",//客戶端向服務器發送請求時採取的方式
contentType: "application/json",//指定客戶端發送給服務器的內容的類型以及服務器返回給客戶端內容的類型爲json格式
url: "WebService1.asmx/ValidateUser",//指明客戶端要向哪個頁面裏面的哪個方法發送請求
data: "{username:'" + $('#txtUserName').val() + "'}",//指定伴隨發送的請求傳遞到服務器的參數
success: function (result) {//客戶端調用服務器端方法成功後執行的回調函數。
$('#spinfo').text(result.d);
}
})
})
})
</script>
</head>
<body>
<div>
用戶名<input type="text" id="txtUserName" /><span id="spinfo"></span><br />
密碼<input type="text" id="txtPwd" />
</div>
</body>
</html>
WebService頁面
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebAjax
{
/// <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 string GetDate()
{
return DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
}
[WebMethod]
public string Login(string username, string pwd)
{
if (username == "admin" && pwd == "888888")
{
return "true";
}
else
{
return "false";
}
}
}
}