ASHX をソースとして jQuery オートコンプリートを使用します。ただし、すべてのリクエストで 200 番のエラーがスローされます。
私のJavaScript:
$(function () {
$('#username input[type = "text"]').autocomplete({
source: function (request, response) {
$.ajax({
url: "UserName.ashx?term=" + request.term,
dataType: "json",
type: "POST",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Value
}
}))
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
});
HTML:
<div id="username">
<asp:Label Text="User name" runat="server" />
<asp:TextBox ID="txtUserName" runat="server" />
</div>
ASHX:
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.Clear()
context.Response.ContentType = "application/json"
Try
Dim oList As New List(Of ResultItem)
For Each File As System.IO.FileInfo In New System.IO.DirectoryInfo(ApplicationInfo.Settings.AbsoluteUserConfigPath).GetFiles(context.Request.QueryString("term") & "*.xml")
oList.Add(New ResultItem With {.Value = System.Text.RegularExpressions.Regex.Replace(File.Name, File.Extension & "$", String.Empty)})
Next
context.Response.Write(New System.Web.Script.Serialization.JavaScriptSerializer().Serialize(oList))
Catch ex As Exception
context.Response.Clear()
context.Response.ContentType = "text/plain"
context.Response.StatusCode = 500
context.Response.StatusDescription = ex.Message
End Try
End Sub
静的コンテンツでは問題なく動作しますが、このリクエストでは次のエラーが発生します: SyntaxError: JSON.parse: unexpected character
.
結果の JSON は次のようになります。
[
{"Value":"Item 1","Name":"","Description":""},
{"Value":"Item 2","Name":"","Description":""},
{"Value":"Item 3","Name":"","Description":""},
{"Value":"Item 4","Name":"","Description":""}
]
有効である必要があります。
なぜそれが機能しないのですか?予想外のキャラクターとは?
返信ありがとうございます。