我已採取一些源代碼from here提交表單使用AJAX。表單基本上是從用戶那裏獲取一些信息,並通過PHP將其放入數據庫中。我的代碼是有效的,但考慮到我正在做的事情有很多形式都在做同樣的事情,我顯然想要確保我的代碼是精簡而且意味深長的。因此,確保我的每一個表單字段名稱都一樣我與形式對用戶反饋的各個部分的一些匹配的ID數據庫,已經改成了以下內容:Javascript代碼運行良好,直到放入函數
<script type="text/javascript">
$(document).ready(function() {
// process the form
$('#formId').submit(function(event) { // for the specified form:
// completeForm('#formId'); // WHERE I CALL THE FUNCTION
// FUNCTION STARTS HERE WHEN IT IS ONE
var formData = {}; formId = '#formId';
$(formId + ' input, ' + formId + ' select, ' + formId + ' textarea').each(
function(index){ // for each item (input, select, textarea in the specified form
var input = $(this);
// First, clear any existing formatting that has been added by previous form inputs
$('#' + input.attr('id') + '-group').removeClass('has-info has-error has-success bg-error bg-info bg-success');
// Next, add data to the array of data to pass to the PHP script
Array.prototype.push.call(formData, input.val());
}
); // End of loop through each item.
// Now the data is collected, call the requested PHP script via AJAX.
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : $(this).attr('action'), // '/processing/general_settings_processing.php', // the url where we want to POST
data : formData, // our data object
dataType : 'html' // 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// Return success and error messages to the user
// Code to come once the basics have been sorted out!
});
// FUNCTION WOULD END HERE WHEN IT IS ONE.
event.preventDefault();
});
});
</script>
代碼爲上述工程絕對好;相關的PHP文件被調用,儘管我沒有在這個特定的文件中完成處理,但是它的東西(我已經將$ _POST數組回傳給一個文件並返回到控制檯日誌atm中查看)。
但是,當我嘗試使其成爲函數時,它不會 - 控制檯日誌只是簡單地迴應該文檔的源代碼,而不是它應該執行的PHP數組。該功能位於$(document).ready
行的上方;指定爲function completeForm(formID) { . . . }
,包含註釋中所述的代碼部分,並在註釋掉的行中調用,如圖所示。所以,邏輯上(對我)它應該工作。
最終的想法是有一個函數可以在所有調用它的表單調用的文件中執行此操作,而調用該函數的代碼位於頁面的相關部分。有些頁面將使用多個表單。 (我提到,即使我在這裏做的工作,它不會當我來重用代碼!)
(我相對較新的JS和JQuery,雖然有一些相當不錯的把握編程技術,這些日子主要只是在PHP中)。
我覺得我應該補充的是,數據從形式收集工作正常時,它是所謂的功能,它很簡單,就是通過AJAX那並不是調用PHP代碼t似乎想要正常工作。 –