Javascript jspostajax的一个通用函数

Javascript jspostajax的一个通用函数,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我正在使用Javascript中的$.post函数将变量发送到php文件,并从php获取输出并在页面上显示 目前,我在每个页面上重复了超过30个类似的代码块,这似乎不是很有效: $(document).on('click', '#forgotpass', function() { var forgotpwd_email = $('#emailreg').val(); .... $.post('include/forgotpwd_link.php', {

我正在使用Javascript中的
$.post
函数将变量发送到php文件,并从php获取输出并在页面上显示

目前,我在每个页面上重复了超过30个类似的代码块,这似乎不是很有效:

  $(document).on('click', '#forgotpass', function() {
    var forgotpwd_email = $('#emailreg').val();
    ....
    $.post('include/forgotpwd_link.php', {
        forgotpwd_email: forgotpwd_email,
        ....
    }, function(a4) {
        $(".loginright").html(a4);
    });
  });
其中:

#forgotpass
-激活脚本的按钮id

#emailreg
-要发送到php文件的值字段的id

.loginright
-div类,我在其中放置响应

每次按钮id、字段id、字段和变量的数量以及php文件名发生变化时。 是否有任何方法可以通过改变字段数量来创建函数,这些字段可以被激活,如下面所示

post_function('#button_id', '{variable1, variable2}', 'div with response from file_name.php','file_name.php');

主要挑战是未定义要发送的变量数量。。可以是一到十五个。

感谢El_Vanja的提示

最后,我创建了以下函数:

function ajax_post(variables, response_selector, phpfile) {
        $.each(variables, function(key) {
          variables[key] = $('#'+key).val();
        });
        $.post(phpfile, variables, function(response) {
            $(response_selector).html(response);
        });

}
ajax_post(variables, '.wrapper', 'test.php');
我将输入ID(即#var1和#var2)添加到变量对象:

var variables = {var1 : '', var2 : ''};
和调用函数:

function ajax_post(variables, response_selector, phpfile) {
        $.each(variables, function(key) {
          variables[key] = $('#'+key).val();
        });
        $.post(phpfile, variables, function(response) {
            $(response_selector).html(response);
        });

}
ajax_post(variables, '.wrapper', 'test.php');
在哪里

变量-具有输入ID的对象(也用作变量名)


.wrapper-div,我想将test.php文件的响应放在其中,只需将所有字段分组到一个对象中即可。在post中传递数据时,数据还是作为对象传递的。您的思路是正确的,只是您的第二个参数不需要是字符串。或者,您可以发送一个标识符数组作为第二个参数,然后让
post_函数
迭代它们,为post请求构建数据对象。