2012-07-10 68 views
1

我想將變量的值傳遞給ajaxForm數據。將值傳遞給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']; 

================== ==== COMPLETE腳本

<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']; 
?> 
+0

所以,你只是想InitCase鍵值名的當前狀態? – Chandu 2012-07-10 17:10:12

+0

我需要在AjaxForm調用期間在JSON中傳遞的變量值? – Shiv 2012-07-10 17:52:26

+0

你現在的代碼應該可以正常工作。你面臨的問題是什麼? – Chandu 2012-07-10 17:54:13

回答

5

您在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); 
     } 
    }); 
})(); 
+0

非常感謝!添加缺少的逗號可以修復該問題 – Shiv 2012-07-10 18:14:34

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";