我遇到了一个问题,我使用 AJAX(JSON) 填充数据列表。我希望能够从数据列表中选择选项并单击“查找时间表”按钮并根据该选定的项目 ID 进行更多的 ajax 调用。我的代码如下所示。
我的 HTML
<div id="datalist" class="hide">
<label id="labelPl" for="projectList">Select your project from the list: </label>
<input type="text" id="ProjName" list="projectList" placeholder=" Project Search by Client's Name : e.g. google, microsoft,caresource etc.">
<datalist id="projectList"></datalist>
<button id="find-ts" class="btn btn-primary">Find Timesheets</button>
</div>
成功填充项目列表的我的 AJAX
$('#ProjName').on('input', function (e) {
var val = $(this).val();
if (val === "") return;
var query = $('#ProjName').val();
var uId=@Model.Id;
$.getJSON("/Search/Projects", { userId: uId, query: query }, function (data, xhr) {
var dataList = $('#projectList');
dataList.empty();
$.each(data, function (i, item) {
var sdate = new Date(parseInt(item.StartDate.substr(6)));
formatStartDate = (sdate.getMonth() + 1) + '/' + sdate.getDate() + '/' + sdate.getFullYear();
var fromatEndDate;
if (item.EndDate == null) {
fromatEndDate = "Present";
}
else {
fromatEndDate = item.EndDate;
}
var opt = $("<option class='selected-project' style='min-height:4em'></option>").attr({
"value":item.Name + " (from " + formatStartDate + " to " + fromatEndDate + ")",
"data-id":item.Id
});
var select=$('<select id="selectList"></select>')
dataList.append(select.append(opt));
});
});
按钮的我的 ONCLICK 事件监听器
$('#find-ts').click(function () {
//get the id of the selected from datalist
var val = $('#ProjName').val()
var selectedId=$('#selectList option:selected').attr('data-id');
var projId = selectedId ? selectedId : 0; //set it to zero if not found
//
console.log("the projectId is ", projId); //This is where I need my projectId so that I can pass in into the controller action method.
$.ajax({
url: 'url?projId=' + projId,
type: 'GET',
beforeSend: function before() {
loadingBar(true);
},
complete: function complete() {
var myVar = setInterval(function () { loadingBar(false); }, 5000);
},
success: function (result) {}
//doing some calculation here
});
});