2012-01-08 97 views
1

我正在做一個post調用,並想設置我通過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> 

回答

0

{postvars}和{N:N}不equivelent,

{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" 
); 
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"); 
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!" 
}