将 CURL 转换为 $.Ajax
Convert CURL to $.Ajax
我正在使用 spotify API,示例代码给了我一个 curl 请求来玩。我试图将其转换为 ajax 请求,但我遇到了一些麻烦。
卷曲代码:
curl -X POST "https://api.spotify.com/v1/users/12166097089/playlists" -H "Accept: application/json" -H "Authorization: Bearer <super long encryption string>" -H "Content-Type: application/json" --data "{\"name\":\"NewPlaylist\",\"public\":false}"
我的尝试AJAX:
function create_playlist(user, hash) {
xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
console.log(xhr.responseText);
}
};
$.ajax({
url:'https://api.spotify.com/v1/users/' + user + '/playlists',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + '<same super long string>');
xhr.setRequestHeader('Accept-Language', 'en_US');
},
type: 'POST',
contentType: 'application/json',
data: {
"name":"Temp Playlist",
"public": false
},
dataType: 'JSON',
success: function (response) {
console.log(response);
},
error: function() {
alert("it failed");
}
});
}
如果发送为 application/json
,需要将数据字符串化。 $.ajax 不会为你这样做
var dataObj = {
"name":"Temp Playlist",
"public": false
}
$.ajax({
......
data: JSON.stringify(dataObj),
dataType: 'JSON',
success: function (response) {
console.log(response);
},
error: function() {
alert("it failed");
}
});
也不需要创建 new XMLHttpRequest()
。这就是 $.ajax
已经在做的事情
我正在使用 spotify API,示例代码给了我一个 curl 请求来玩。我试图将其转换为 ajax 请求,但我遇到了一些麻烦。
卷曲代码:
curl -X POST "https://api.spotify.com/v1/users/12166097089/playlists" -H "Accept: application/json" -H "Authorization: Bearer <super long encryption string>" -H "Content-Type: application/json" --data "{\"name\":\"NewPlaylist\",\"public\":false}"
我的尝试AJAX:
function create_playlist(user, hash) {
xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
console.log(xhr.responseText);
}
};
$.ajax({
url:'https://api.spotify.com/v1/users/' + user + '/playlists',
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + '<same super long string>');
xhr.setRequestHeader('Accept-Language', 'en_US');
},
type: 'POST',
contentType: 'application/json',
data: {
"name":"Temp Playlist",
"public": false
},
dataType: 'JSON',
success: function (response) {
console.log(response);
},
error: function() {
alert("it failed");
}
});
}
如果发送为 application/json
,需要将数据字符串化。 $.ajax 不会为你这样做
var dataObj = {
"name":"Temp Playlist",
"public": false
}
$.ajax({
......
data: JSON.stringify(dataObj),
dataType: 'JSON',
success: function (response) {
console.log(response);
},
error: function() {
alert("it failed");
}
});
也不需要创建 new XMLHttpRequest()
。这就是 $.ajax
已经在做的事情