3

我需要做一个 POST 请求,例如:

POST /feeds/api/users/default/subscriptions HTTP/1.1
Host: gdata.youtube.com
Content-Type: application/atom+xml
Content-Length: CONTENT_LENGTH
Authorization: Bearer ACCESS_TOKEN
GData-Version: 2
X-GData-Key: key=DEVELOPER_KEY

<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
  xmlns:yt="http://gdata.youtube.com/schemas/2007">
    <category scheme="http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat"
      term="channel"/>
    <yt:username>GoogleDevelopers</yt:username>
</entry>

例如,我知道如何在服务器(.NET/C#)端使用HttpWebRequest对象、设置 Header/Method/ContentType。

但是如果我想在客户端做呢?使用 jQuery 的 Ajax?我在哪里可以设置这些参数?

4

1 回答 1

4

您可以使用此功能:

function post(url, data, headers, success) {
    $.ajax({
        beforeSend: function(xhr){
            $.each(headers, function(key, val) {
                xhr.setRequestHeader(key, val);
            });
            xhr.setRequestHeader('Content-Length', data.length);
        }
        type: "POST",
        url: url,
        processData: false,
        data: data,
        dataType: "xml",
        success: success
    });
}

使用这样的代码:

var request = '<?xml version="1.0" encoding="UTF-8"?>' +
       '<entry xmlns="http://www.w3.org/2005/Atom"' +
       '        xmlns:yt="http://gdata.youtube.com/schemas/2007">' +
       '    <category scheme="http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat" term="channel"/>'+
       '    <yt:username>GoogleDevelopers</yt:username>' +
       '</entry>';

var headers = {
   'Content-Type': 'application/atom+xml',
   'Authorization': 'Bearer ACCESS_TOKEN'
   'GData-Version': 2
   'X-GData-Key': 'key=DEVELOPER_KEY'
};

post('/some/url', request, headers, function(response) {
   alert(response);
});
于 2013-08-20T12:57:00.103 回答