如何动态设置后置变量?

时间:2012-01-08 18:20:32

标签: jquery

我正在进行一次调用,并希望设置我通过一些if / else语句动态发送的参数。以下简化版本不起作用,但如果我将'{postvars}'更改为'{n:n}'那么它确实如此,即使它们是等效的,对吧?

<html>
<head>
<title></title>
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript">
   $(document).ready(function () {

   $("#clicky").click(function () {
     var postvars; var mydata;
     var n = 'dave';
     postvars = 'n: ' + n;

      $.post("test.php", 
     {postvars}, 
      function(data){
          }, 
        "text"
        );  

$("#test").text(postvars);

  });
   });
</script>
</head>
<body>

<div id='clicky'>click here</div>
<div id='test'></div>

</body>


</html>

3 个答案:

答案 0 :(得分:1)

试试这样:

// define an empty object
var data = { };

var variableName = 'n';
var variableValue = 'dave';

// assign properties of the data object dynamically
data[variableName] = variableValue;
...

然后发布您动态构建的data变量:

$.post("test.php", data, function(result) {
    alert(result);
}, "text");

答案 1 :(得分:0)

{postvars}和{n:n}不等同,

{postvars}将被视为javascript作为对象initalizer,并将作为postvars错误输出只是一个字符串,它不能自己设置对象的属性/值。

{n:n},但是它是一个适当的对象initalizer,因为它给出了名称和值

jquery ajax函数采用名称值对字符串

  $.post("test.php", 
         "data=somedata&moredata=thisdata", 
         function(data){
         }, 
         "text"
  );  

或json对象,

var newData = "Some new data";
var data = {
     "dataname":"datavalue";
};

//add dynamic variables to object
data["newData"] = newData;

$.post("test.php", 
       data, 
       function(data){
       }, 
       "text"
 );  

答案 2 :(得分:0)

如果要获取表单的变量,可以使用serialize()函数来获取参数字符串。 http://api.jquery.com/serialize/

如果要从对象获取参数字符串,则必须使用$.param()函数: http://api.jquery.com/jQuery.param/

像这样:

function someFunc() {
    var obj=new Object();
    obj.n=1;
    obj.str="Hello!";

    var dataStr=$.param(obj);
   //dataStr is now "n=1&str=Hello!"
}
相关问题