我想ajax发布依赖于我的变量的数据。 我试过以下但没有运气..
var datastring = "name:name,price:price,specialprice:specialprice,desc:desc,descs:descs,cat:cat,pictures:pictures,choiceimg:choiceimg,weight:weight,gtin:gtin,brand:brand,attid:attid";
if($("#color").val()) {
var color = $("#color").val();
datastring = datastring + ",color:color"
}
$.ajax({
type: 'POST',
data:{ datastring },
success: function() { },
error: function(){ },
url: 'insert.php',
cache:false
});
这是一个字符串
datastring
name:name,price:price,specialprice:specialprice,desc:desc,descs:descs,cat:cat,pictures:pictures,choiceimg
:choiceimg,weight:weight,gtin:gtin,brand:brand,attid:attid
任何想法/解决方案?
答案 0 :(得分:1)
假设在定义参数时,您需要创建对象:
var name = ....;
var price = ....;
.....
var datastring = {
name: name,
price: price,
specialprice: specialprice,
'three words property': 'value',
......
};
您可以将属性添加/更改为对象(在声明之后),如此
datastring.myNewProperty = "myString"; // ADD
datastring.name = "New Name"; // UPDATE
datastring['three words property'] = "New Value"; // UPDATE
然后将其传递给服务器:
$.ajax({
type: 'POST',
data: datastring, // Note - I removed the wrapping "{" and "}"
success: function() { },
error: function(){ },
url: 'insert.php',
cache:false
});
答案 1 :(得分:1)
这不是有效的表单编码字符串,并且用于data
属性的语法无效。
最简单的方法是使用一个对象,让jQuery从该对象中为你编码:
var postData = {
name: // name value ,
...
desc: // desc value
...
attid: // attid value
}
if($("#color").val()) {
postData.color = $("#color").val();
}
然后将该对象传递给$.ajax
$.ajax({
type: 'POST',
data: postData ,
success: function() { },
error: function(){ },
url: 'insert.php',
cache:false//redundant since POST will never be cached
});