我怎样才能让一个自定义的" POST"要求在客户端?自定义、客户端、QUOT、POST

由网友(曲终人散ヾ记忆里的伤痛)分享简介:我需要做一个POST请求,如:I need to do a POST request such as:POST /feeds/api/users/default/subscriptions HTTP/1.1Host: gdata.youtube.comContent-Type: application/atom...

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

I need to do a POST request such as:

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 对象,设置页眉/方法/ ContentType的。

I know how to do it server (.NET/C#) side for example, using HttpWebRequest object, settings Header/Method/ContentType.

但是,如果我愿意做客户端?阿贾克斯与jQuery?我在哪里可以设置这些参数?

But if I'd like to do it client side? Ajax with jQuery? Where can I set those parameters?

推荐答案

您可以使用此功能:

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

使用code是这样的:

using code like this:

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);
});
阅读全文

相关推荐

最新文章