簡體   English   中英

正常運行之前的Javascript代碼

[英]Javascript code running fine until put into a function

從這里獲取了一些源代碼以使用AJAX提交表單。 該表單基本上是從用戶那里獲取一些信息,然后通過PHP將其放入數據庫中。 我擁有的代碼可以工作,但是鑒於我正在處理的代碼有很多形式都在做同樣的事情,我-很顯然-我想確保我的代碼精簡而卑鄙。 因此,要確保我的每個表單字段名稱都與數據庫相同,並且具有用於表單各個部分的一些匹配ID以供用戶反饋,請將其更改為以下內容:

<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) { . . . } function completeForm(formID) { . . . } function completeForm(formID) { . . . } ,包含注釋中提到的代碼部分,並在注釋掉的行中調用,如圖所示。 因此,從邏輯上(對我而言)它應該可以工作。

最終的想法是讓函數在一個文件中執行此操作,所有調用該文件的表單都可以調用該文件,而調用該函數的代碼在頁面的相關部分中。 某些頁面將使用多種形式。 (我提到即使我在這里做的事情都能奏效,當我重用代碼時也不會!)

(盡管我對JS和JQuery相對較新,但是對某些編程技術掌握得相當好,主要是最近幾天才使用PHP。)

使函數產生的問題是您忘記包含“ thisBinding”。 結果,當您嘗試使用以下代碼在ajax調用中使用表單的操作目標時:

url : $(this).attr('action')

它沒有找到“動作”屬性-基本上,問題是this實際上是window ,因此沒有動作屬性。 簡單地綁定this到你的函數調用,你的代碼將作為寫入。

completeForm.call(this,'#formId');

.call MDN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM