为什么Jquery GET请求不返回任何数据?

时间:2011-10-15 17:19:47

标签: php jquery greasemonkey

$.get("http://localhost/code.php", function(data){
alert(data);
});

code.php:

<?php
echo "hello!";
?>

我也试过过post和ajax的其他变种,没什么用。我可以正常运行php脚本,例如我可以写入文件,但是它们不返回任何数据。

我正在IIS服务器上运行脚本。

[编辑]

我忘了添加一个重要的细节,我从一个greasemonkey脚本调用php脚本。我在服务器上尝试了它,它的工作原理。但是我需要这个换油脂。

3 个答案:

答案 0 :(得分:1)

如果您通过GreaseMonkey , the prefix调用来自远程页面的方法,则必须添加unsafeWindow。

unsafeWindow.$.get("http://localhost/code.php", function(data){
    alert(data);
});

如果您不需要特定于JQuery的方法,我建议您使用GM_xmlhttpRequest

GM_xmlhttpRequest({
    "method": "get",
    "url": "http://localhost/code.php",
    "onload": function(data){
        alert(data);
    }
})

答案 1 :(得分:0)

this blog post判断,Greasemonkey不提供jQuery使用的XHR对象,所以你必须包装它提供的内容并使用自定义实现设置jQuery AJAX。

我将在此引用相关代码:

// Wrapper for GM_xmlhttpRequest
function GM_XHR() {
    this.type = null;
    this.url = null;
    this.async = null;
    this.username = null;
    this.password = null;
    this.status = null;
    this.headers = {};
    this.readyState = null;

    this.open = function(type, url, async, username, password) {
        this.type = type ? type : null;
        this.url = url ? url : null;
        this.async = async ? async : null;
        this.username = username ? username : null;
        this.password = password ? password : null;
        this.readyState = 1;
    };

    this.setRequestHeader = function(name, value) {
        this.headers[name] = value;
    };

    this.abort = function() {
        this.readyState = 0;
    };

    this.getResponseHeader = function(name) {
        return this.headers[name];
    };

    this.send = function(data) {
        this.data = data;
        var that = this;
        GM_xmlhttpRequest({
            method: this.type,
            url: this.url,
            headers: this.headers,
            data: this.data,
            onload: function(rsp) {
                // Populate wrapper object with returned data
                for (k in rsp) {
                    that[k] = rsp[k];
                }
            },
            onerror: function(rsp) {
                for (k in rsp) {
                    that[k] = rsp[k];
                }
            },
            onreadystatechange: function(rsp) {
                for (k in rsp) {
                    that[k] = rsp[k];
                }
            }
        });
    };
};

设置jQuery的AJAX:

$.ajaxSetup({
    xhr: function(){return new GM_XHR;}
});

在此步骤之后,.get()和其他AJAX方法应该可以正常工作。

答案 2 :(得分:0)

好吧,最后我放弃了greasemonkey,因为无论我尝试什么都行不通。所以我得到了脚本,幸运的是,我需要的代码只是再次点击插件页面。所以在这里,如果有其他人需要它:

var ret = GM_xmlhttpRequest({
  method: "GET",
  url: "http://localhost/code.php",
  onload: function(res) {
    alert(res.responseText);
  }
});

它可以立即用于编写脚本,不需要包含任何其他内容。