我需要执行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。
但如果我想做客户端呢? Ajax与jQuery?我在哪里可以设置这些参数?
答案 0 :(得分:2)
您可以使用此功能:
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);
});