上下文: 我工作的學生在webapp中轉錄紙質報告。這是舊的,我們不幸的是不能改變源代碼,也不能直接運行數據庫查詢。在沒有iframe的情況下使用JavaScript提交表單/獲取HTML?
它只會在您提交整個表單時檢查唯一標識是否存在,除非它完全填充,否則無法提交。不用說,這是一個巨大的浪費時間,因爲你經常只是轉錄整個事物才意識到它是重複的。
目的: 我做了下面的userscript啓動一個搜索的唯一ID的輸入的onblur(noReferenceDeclarant)搜索,檢查是否有任何匹配(行),並相應地返回。用Greasemonkey運行。搜索表單位於同一個域的另一個頁面中。搜索表單不包含任何網址參數。
可以這樣不使用iframe來完成(AJAX吧?) 這是我自己的生產力&學習JS在同一時間的工具。由於我仍然是初學者,因此歡迎任何提示使代碼更清潔的技巧。
//Adding function to input's blur event
$(document).on ("blur", "#noReferenceDeclarant", isRefNumberExists);
//Vars
var noReferenceDeclarant = '';
var loadCode = 0;
var $searchForm;
//Fonctions
function isRefNumberExists()
{
noReferenceDeclarant = $('#noReferenceDeclarant').val();
loadCode = 0;
//Make sure there's data in the input before proceeding
if (noReferenceDeclarant)
{
//Build search iframe
$searchForm = $('<iframe />', {
name: 'searchWindow',
src: 'rechercherGriIntranet.do?methode=presenterRechercher',
id: 'searchWindow',
width: 0,
height: 0
}).appendTo('body');
$searchForm.load(searchRefNumber);
}
}
function searchRefNumber()
{
var isExists = false;
//Check which "load" it is to avoid submit loops
if (loadCode === 0)
{
loadCode = 1;
//Filling search form with search term
$(this.contentDocument).find('#noReference').val(noReferenceDeclarant);
//Set search form preferences
$(this.contentDocument).find('#typeRapportAss').prop('checked', false);
$(this.contentDocument).find('#typeRapportAS').prop('checked', false);
$(this.contentDocument).find('#typeRapportSI').prop('checked', true);
//Submit the form
$(this.contentDocument).find('form:first').submit();
}
else if (loadCode === 1)
{
loadCode = 2;
//See if there are any tr in the result table. If there are no results, there a thead but no tr.
var foundReports = $(this.contentDocument).find('.resultatRecherche tr').length;
if (foundReports > 0)
{
if (confirm('A report matching this ID already exists. Do you want to display it?'))
{
//Modal window loading the report in an iframe. Not done yet but that's fairly straightforward.
}
else
{
//Close and return to the form.
}
}
}
//Reset variables/clean ressources
delete $searchForm;
$('#dateRedactionRapport').focus();
}
謝謝。對不起,我的延期回答,我假期工作:) loadCode的需求是檢查我已經達到了哪一步,否則每次載入iframe時執行onload操作,因此導致循環。 我覺得使用數字已經足夠清楚到達哪個步驟。 – tsc
感謝關於_semaphores_的筆記,學習正確的術語/語義絕對是遊戲的一部分!我會花一些時間閱讀一些內容。所有其他正式注意到的並將很快實施。非常感謝您的幫助。 – tsc