| $(document).ready(function () { $('#update').bind('click', GetDocuments); $('#search').bind("keydown", GetInput); $("#search").autocomplete({ source: function (request, callback) { GetAutocomplete(); callback(Documents); }, open: function (event) { var $ul = $(this).autocomplete("widget"); } }); }); |
当你点击"update"按钮的时候会执行GetDocuments方法。它会进行一次全文检索然后将结果显示到一个HTML表格中:
| function GetDocuments(e) { var searchstring = $('#search').val(); if (searchstring.length > 0) { if (searchstring[searchstring.length - 1] != "*") { searchstring += "*"; } } $.ajax({ type: 'POST', url: 'http://localhost:8001/VisionService.svc/GetDocuments', dataType: 'json', crossDomain: true, data: JSON.stringify({ search: searchstring, format: 1, forautocomplete: 0 }), processData: true, contentType: "application/json ; charset=utf-8", success: function (json, textStatus) { var result = JSON.parse(json); var display; display = ""; display += "<table id='mytable' border=2 <thead><th style='text-align:left' >ID</th><th style='text-align:left' >Title</th><th style='text-align:left' >Text</th></thead><tbody>"; $.each(result, function (index, value) { display += "<tr>"; display += "<td>" + value.DocumentID + "</td>"; display += "<td>" + value.Title + "</td>"; display += "<td>" + value.Text + "</td>"; display += "<tr>"; }); display += "</tbody></table>"; $('#result').empty() $('#result').html(display); }, error: function (xhr, textStatus, errorThrown) { alert('An error occurred! ' + (errorThrown ? errorThrown : xhr.status) + " xhr: " + xhr + " textStatus: " + textStatus); } }); } |
我们把查询表单中"search"字段的值付给变量searchstring,然后,当searchstring中不包含"*"通配符的时候,我们在其后面添加通配符"*",jQuery提供了对Ajax的支持,比如$.ajax()方法。
你可以从这儿查看关于这个方法的说明:jQuery.ajax()。
url:制定了我们在WCF应用中配置好的路径。就如我们在WCF应用中设置的一样,我们使用JSON数据格式。在success方法(这个方法会在ajax请求成功后被异步调用)中,我们获取了json变量,也就是GetDocuments方法输出的值。通过简单的调用JSON.parse(json)方法,我们获得了一个完全成熟的JavaScript对象,我们使用这个对象生成Html表格。result>变量是一个JavaScript对象数组。jquery的$.each方法遍历整个数组,当方法执行的时候,使用当前数组元素的索引和处于当前索引位置的元素作为参数。我们通过调用$('#result').html(display)来显示Html代码,从而生成我们的结果DIV。底层数据:我们使用JSON.stringify方法将用来传输的数据转化为JavaScript对象并将其作为参数。当发生错误的时候,在error:后面的代码将会执行。










