【问题标题】:Passing value to ajaxform data将值传递给 ajaxform 数据
【发布时间】:2012-07-10 17:04:45
【问题描述】:

我想将变量的值传递给 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>

form-php.php

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

【问题讨论】:

  • 所以你只想初始化键名?
  • 我需要在 AjaxForm 调用期间在 JSON 中传递一个变量值?
  • 您现在拥有的代码应该可以正常工作。您面临的问题是什么?
  • 无法使用以下方法获取值:echo $_POST['key1'];在 php 中
  • @Chandu:请参考我的帖子,我添加了完整的脚本...

标签: jquery


【解决方案1】:

数据属性后缺少逗号。

试试这个:

(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);
        }
    });
})();

【讨论】:

  • 非常感谢!添加缺少的逗号修复了该问题
  • 我可以通过这种方式传递一个blob文件来上传数据吗?
【解决方案2】:

给定解决方案的问题是,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";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2012-10-24
    • 1970-01-01
    相关资源
    最近更新 更多