1

我想将变量的值传递给 ajaxForm 数据。

value1 = "dynamic_value1";
value2 = "dynamic_value2";
$('form').ajaxForm({
    data: {
      key1: value1, 
      key2: value2 
    }
});

期待类似的东西:

date:{Key1:"dynamic_value1", Key2:"dynamic_value2"}

所以在php中我可以访问

echo $_POST['key1'];

======================= 完成脚本

<script src="../../bin/addons/jquery-1.7.2.js"></script>
<script src="../../bin/addons/jquery.form.js"></script>
<script>
// jQuery Form-plugin 
(function() {
  var value1 = "dynamic_value1";
  var value2 = "dynamic_value2";
  $('.dummyForm1').ajaxForm({
    data:{
      key1: value1,
      key2: value2
  }
  complete: function(xhr) {
      txt = xhr.responseText;
      alert(txt);
  }
}); 
})(); 
</script>

<form class="dummyForm1" action="form-php.php" method="post">
    <input type="submit" value="Hit!" />
</form>

表单-php.php

<?
  echo "Key1 value:". $_POST['key1'];
?>
4

2 回答 2

6

您在 data 属性后缺少逗号。

试试这个:

(function () {
    var value1 = "dynamic_value1";
    var value2 = "dynamic_value2";
    $('.dummyForm1').ajaxForm({
        data: {
            key1: value1,
            key2: value2
        }, //You were missing this comma.
        complete: function (xhr) {
            txt = xhr.responseText;
            alert(txt);
        }
    });
})();
于 2012-07-10T18:09:37.800 回答
1

给定解决方案的问题是 ajaxform 将在调用事件处理程序时填充变量。

var value1 = "dynamic_value1";
/*This will be sent*/
var value2 = "dynamic_value2";
(function () {
    $('.dummyForm1').ajaxForm({
        data: {
            /*On load of event handler the values are set, they are not dynamic anymore*/
            key1: value1,
            key2: value2
        },
        complete: function (xhr) {
            txt = xhr.responseText;
            alert(txt);
        }
    });
})();
/*This will not be sent*/
value2 = "new value";

您可以使用函数返回全局变量的当前状态

var value1 = "dynamic_value1";
/*This will not be sent*/
var value2 = "dynamic_value2";
(function () {
    $('.dummyForm1').ajaxForm({
        data: {
            /*On load of event handler the values are set, they are not dynamic anymore*/
            key1: value1,
            key2: function () {
                /*this returns the current state of the global variable*/
                return value2;
            }
        },
        complete: function (xhr) {
            txt = xhr.responseText;
            alert(txt);
        }
    });
})();
/*This will be sent*/
value2 = "new value";
于 2015-08-12T20:11:51.453 回答