gpt4 book ai didi

Javascript 代码在放入函数之前运行良好

转载 作者:行者123 更新时间:2023-12-01 05:33:36 25 4
gpt4 key购买 nike

我拿了一些源代码from here使用 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) { . . . } ,包含注释中注明的代码部分,并在注释掉的行中调用,如图所示。所以,从逻辑上(对我来说)它应该有效。

最终的想法是在一个文件中提供执行此操作的函数,所有调用该函数的表单都可以调用该函数,而调用该函数的代码位于页面的相关部分中。某些页面将有多个表单使用它。 (我提到即使我在这里所做的事情有效,当我重用代码时它也不会起作用!)

(我对 JS 和 JQuery 相对较新,尽管对一些编程技术有相当好的掌握,目前主要是 PHP。)

最佳答案

您在创建该函数时遇到的问题是您忘记包含“thisBinding”。因此,当您尝试使用以下代码在 ajax 调用中使用表单的操作目标时:

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

它没有找到“action”属性 - 基本上问题是 this 实际上是 window 并且因此没有 action 属性。只需将 this 绑定(bind)到您的函数调用,您的代码就会按编写的方式工作。

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

.call MDN

关于Javascript 代码在放入函数之前运行良好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35374109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com