名称

GM_xmlhttpRequest — 进行任意的 HTTP 请求

大纲

GM_xmlhttpRequest ( details );

描述

GM_xmlhttpRequest 建立任意的 HTTP 请求。 详细 参数是一个有七个域的对象。

method
字符串,请求使用的方法 HTTP必需。 通常使用 GET,但也可使任一个 HTTP 动词,包含 POST, PUTDELETE
url
字符串,请求使用的 URL必需。
headers
这个请求包含的 HTTP 头的关联数组。可选,默认为空字符串。例如:
headers: {'User-Agent': 'Mozilla/4.0 (compatible) Greasemonkey',
'Accept': 'application/atom+xml,application/xml,text/xml'}
data
字符串,HTTP 请求的主体。可选,默认是空字符串。如果您在模拟提交表单(method == 'POST'),在 headers 域中必需有 Content-type,值为 'application/x-www-form-urlencoded',而且在 data 域包含有 URL 编码后的表单数据。
onload
函数对象,请求成功完成调用的回调函数。
onerror
函数对象,执行请求发生错误时调用的回调函数。
onreadystatechange
函数对象,请求进行时反复调用的回调函数。

onload 回调

onload 的回调函数,有一个变量,responseDetails

function onloadCallback (   responseDetails );

responseDetails 是有五个域的对象。

status
整数,HTTP 应答的状态代码。200 意为请求正常完成。
statusText
字符串,HTTP 状态文字。状态文字是依赖于服务器的。
responseHeaders
字符串,应答包含的 HTTP 头部。
responseText
字符串,应答的主体。
readyState
未使用

onerror 回调

onerror 的回调函数,有一个参数,responseDetails

function onerrorCallback (   responseDetails );

responseDetails 是有五个域的对象。

status
整数,HTTP 的错误代码。404 意为页面无法找到。
statusText
字符串,HTTP 状态文字。状态文字是依赖于服务器的。
responseHeaders
字符串,应答包含的 HTTP 头部。
responseText
字符串,应答的主体。HTTP 错误页面的主体是依赖于服务器的。
readyState
未使用

onreadystatechange 回调

onreadystatechange 的回调函数,当请求正在进行时反复调用。有一个参数,responseDetails

function onreadystatechangeCallback (   responseDetails );

responseDetails 是有五个域的对象。responseDetails.readyState 指示了请求当前所在的阶段。

status
整数,应答的 HTTP 状态代码。当 responseDetails.readyState < 4时,这个值是0
statusText
字符串,HTTP 状态文字。当 responseDetails.readyState < 4时,这个值是空字符串。
responseHeaders
字符串,应答包含的 HTTP 头。当 responseDetails.readyState < 4时,这个值是空字符串。
responseText
字符串, 应答的主体。当 responseDetails.readyState < 4时,这个值是空字符串。
readyState
整数,the stage of the HTTP request。
1
正在载入。请求已准备好。
2
已加载。请求准备发送到服务器,但是还什么都没发。
3
交互状态。请求已经发送,并且客户端等待服务器完成发送数据。
4
完成。请求已完成,并且其他域中的所有应答数据已可用。

例子

下面的代码从http://greaseblog.blogspot.com/获取 Atom feed,然后用警告窗口显示结果。

GM_xmlhttpRequest({
method: 'GET',
url: 'http://greaseblog.blogspot.com/atom.xml',
headers: {
'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
'Accept': 'application/atom+xml,application/xml,text/xml',
},
onload: function(responseDetails) {
alert('Request for Atom feed returned ' + responseDetails.status +
' ' + responseDetails.statusText + '\n\n' +
'Feed data:\n' + responseDetails.responseText);
}
});

Bugs

onreadystatechange 回调函数当 readyState < 4时,工作不正常。

注释

与 XMLHttpRequest 对象不同,GM_xmlhttpRequest 并不限制与当前域名;它能够从任何 URL GET 或者 POST 数据。

← GM_registerMenuCommand
GM_openInTab →