所以,我是新來的JSON/AJAX/jQuery的/ web服務驗證用戶名Ajax和JSON和asp.net
我試圖做一個連接頁面由此幾個字母的用戶類型和獲得的即時反饋無論用戶名是否可用。
我有一個HTML文件[用戶前端],和ASMX web服務,web服務檢查,看是否任何文本已經得到了存在[運行存儲過程的正常工作]
我的HTML文件似乎不是調用我的web服務。
我已通過訪問asmx頁面並手動輸入值來驗證webservice的工作原理,並且它爲我返回true或false。
一個問題是它似乎是回到它在XML,如下圖所示,而不是JSON我是它是在
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://localhost">{"available": false}</string>
所以到代碼/標記!
我的HTML文件
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
$(document).ready(function() {
var validateUsername = $('#validateUsername');
$('#username').keyup(function() {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validateUsername.removeClass('error').html('<img src="images/ajax-loader.gif" height="16" width="16" /> checking availability...');
this.timer = setTimeout(function() {
$.ajax({
contentType: "application/json; charset=utf-8",
url: 'ValidateUser.asmx/GetUsernameAvailable',
data: '{username: "'+t.value + '"}',
dataType: 'json',
type: "post",
success: function (j) {
validateUsername.html('I willl have my logic in here for changing the html on the label to reflect success or failure!');
}
});
}, 200);
this.lastValue = this.value;
}
});
});
//-->
</script>
</head>
<body>
<fieldset>
<div>
<label for="username">Username, valid: a-z.-_</label>
<input type="text" name="username" value="" id="username" />
<span id="validateUsername"></span>
</div>
</fieldset>
</body>
</html>
我ASMX文件
<%@ WebService Language="C#" Class="ValidateUser" %>
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.Odbc;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using UserSite.DataClasses;
[WebService(Description = "Web services to query Username availability.", Namespace = "http://localhost")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class ValidateUser: System.Web.Services.WebService
{
[WebMethod(Description = "Gets the availability of a username.")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetUsernameAvailable(string username)
{
if (username == null)
{
username = "";
}
DbaseExecSpWithReturnValue Sproc = new DbaseExecSpWithReturnValue();
Sproc.SetSp("sp_CheckUsernameAvailable");
Sproc.AddParam(1);
Sproc.AddParam("Username", SqlDbType.Char, username, 20);
int RetVal = Sproc.Execute();
Sproc.Close();
if (RetVal == 0)
{
return @"{""available"": false}";
}
else
{
return @"{""available"": true}";
}
}
}
所以存儲過程的工作,因爲我看到的時候我手動跑了ASMX文件,但是HTML頁面並不調用它,我ASMX文件沒有返回數據.....所以基本上它驅使我堅果!
哇,完全工作...我有適當的web.config,但我不明白,它的服務將它轉換爲我[這是合乎邏輯的]。非常感謝! – Jordan 2011-03-09 05:08:15