2011-10-15 42 views
0
$.get("http://localhost/code.php", function(data){ 
alert(data); 
}); 

code.php:爲什麼Jquery GET請求不返回數據?

<?php 
echo "hello!"; 
?> 

我也試圖與崗位和Ajax等變種,沒有什麼工作。我可以運行php腳本就好了,例如我可以寫入一個文件,但是他們沒有返回任何數據。

我正在IIS服務器上運行腳本。

[編輯]

我忘了添加一個重要的細節,我打電話從Greasemonkey的腳本PHP腳本。我在服務器上試過了,它工作。但我需要這個用於油鯉魚。

+8

所以如果你去http://localhost/code.php,你看到了什麼?另外,我假設你是從http:// localhost /提供的頁面調用它的,對吧? –

+2

你的JS控制檯說什麼?任何錯誤? – Quentin

+0

你的服務器日誌呢?你能確認它正在接收請求嗎? – Quentin

回答

0

那麼,最後我放棄了greasemonkey,因爲它不會工作,無論我嘗試什麼。所以我得到了劇本,並且幸運的是,我需要的代碼只是從插件頁面單擊另一個點擊。所以這裏如果有其他人需要它:

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

它可以馬上使用,不需要包含任何其他內容。

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); 
    } 
}) 
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方法應很好地工作。