https://jsfiddle.net/c7n34e3x/1/在 data
/data1
/data2
中只有 data
有效,但它不是动态的
这行得通
var settings = {
"async": true,
"crossDomain": true,
"url": "https://domain/api/v2/playlists/",
"method": "POST",
"headers": {
"content-type": "application/json",
"cache-control": "no-cache",
},
"processData": false,
"data": "{\"playlist_content\" :{\"content_id\" : \"ef0a30ef-3198-4ce6-8927-e390257776ed\"}}"
}
但我需要像下面这样动态的数据。请参阅 content_id
var content_id = $(this).val();
var settings = {
"async": true,
"crossDomain": true,
"url": "https://domain/api/v2/playlists/",
"method": "POST",
"headers": {
"content-type": "application/json",
"cache-control": "no-cache",
},
"processData": false,
"data": "{\"playlist_content\" :{\"content_id\" : \""+content_id+"\"}}"
}
但这行不通。我该怎么做才能动态创建数据设置?这可能会通过语法突出显示更好地阅读。
"data": {"playlist_content": {"content_id": content_id}}
这也行不通
这是一个带有临时标记的 fiddle https://jsfiddle.net/c7n34e3x/
最佳答案
你试过这样吗?
var content_id = $(this).val();
var data = JSON.stringify({"playlist_content" : {"content_id" : content_id}});
var settings = {
"async": true,
"crossDomain": true,
"url": "https://domain/api/v2/playlists/",
"method": "POST",
"headers": {
"content-type": "application/json",
"cache-control": "no-cache",
},
"processData": false,
"data": data
}
根据 JSFiddle 演示更新代码确定 here .它每次都可以使用适当的凭据。
关于javascript - 如何在ajax请求中生成动态数据对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43403614/