[英]Jquery ajax post data
我想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
有什么想法/解決方案嗎?
假設已定義參數,這是創建對象的方式:
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
});
這不是有效的表單編碼字符串,並且用於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
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.