【问题标题】:Why is GM_xmlhttpRequest ignoring its data parameter?为什么 GM_xmlhttpRequest 忽略它的 data 参数?
【发布时间】:2013-02-12 20:56:00
【问题描述】:

根据its documentationGM_xmlhttpRequest 应该能够将data 参数作为其参数的一部分。

但是,我似乎无法让它工作。

我有一个简单的服务器来回显给它的参数:

require 'sinatra'
require 'json'
get '/' do
  JSON.dump params
end
post '/' do
  JSON.dump params
end

还有一个简单的greasemonkey 脚本,它只是尝试将一些数据发布到服务器。 它尝试将数据作为 URL 中的查询参数和 postdata 传递:

// ==UserScript==
// @name        PostDataTest
// @namespace   Test
// @description Simple test of GM_xmlhttpRequest's data parameter
// @include     http://localhost:4567/
// @version     1
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @grant       metadata
// @grant       GM_xmlhttpRequest
// ==/UserScript==

var url = '/?q0=0&q1=1';
var data = 'd0=0&d1=1'

GM_xmlhttpRequest({ method: 'POST', url: url, data: data, onload: function(r){
  console.log('gm:' + r.responseText);
}});
$.post(url, data, function(d,s,r){
  console.log('jq:' + r.responseText);
});

当我使用 jQuery 发布 postdata 时,它可以正常工作,但是我使用 GM_xmlhttpRequest 发布的任何 postdata 都会被忽略:

jq:{"q0":"0","q1":"1","d0":"0","d1":"1"}
gm:{"q0":"0","q1":"1"}

这让我相信GM_xmlhttpRequest 实际上并没有使用我给它的data 参数。 (我不确定 b/c 我无法在 Firebug 中监控 GM_xmlhttpRequest 的网络活动)。

这里发生了什么?我搞砸了什么吗? API是否发生了变化?如何使用GM_xmlhttpRequest 发布数据而不将其打包到 URL 中?

【问题讨论】:

    标签: post greasemonkey gm-xmlhttprequest


    【解决方案1】:

    好的,我使用 TamperData firefox add-on 来监控我的 GM_xmlhttpRequests(发送 postdata),看看他们做了什么不同的事情。

    区别在于四个标题。 jQuery 发送到哪里

    Accept:             */*
    Content-Type:       application/x-www-form-urlencoded; charset=UTF-8
    X-Requested-With:   XMLHttpRequest
    Referer:            http://localhost:4567/
    

    GM_xmlhttpRequest已发送:

    Accept:             text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    Content-Type:       text/plain; charset=UTF-8
    

    使用headers: 参数,我能够指定我的GM_xmlhttpRequestContent-Type,这样它就可以工作了。

    // ==UserScript==
    // @name        PostDataTest
    // @namespace   Test
    // @description Simple test of GM_xmlhttpRequest's data parameter
    // @include     http://localhost:4567/
    // @version     1
    // @require     http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
    // @grant       metadata
    // @grant       GM_xmlhttpRequest
    // ==/UserScript==
    
    var url = '/?q0=0&q1=1';
    var data = 'd0=0&d1=1'
    
    GM_xmlhttpRequest({
      method: 'POST',
      url: url+'gm',
      data: data+'gm',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
      onload: function(r){
        console.log('gm:' + r.responseText);
    }});
    $.post(url+'jq', data+'jq', function(d,s,r){
      console.log('jq:' + r.responseText);
    });
    
    猜你喜欢
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    • 2021-06-22
    • 2019-07-02
    相关资源
    最近更新 更多