weixin_33670786 2015-10-10 01:57 采纳率: 0%
浏览 219

如何将CURL转换为$ .Ajax?

我正在使用Spotify API,示例代码给了我一个cURL请求来处理。我试图将它转换为Ajax请求,但我遇到了一些麻烦。

Curl 代码:

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");
        }
    });
}
  • 写回答

1条回答 默认 最新

  • weixin_33682790 2015-10-10 02:32
    关注

    Need to stringify the data if sending as application/json. $.ajax won't do that for you

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

    Also no need to create a new XMLHttpRequest(). That's what $.ajax is already doing

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘