2016-01-15 18 views
0

我有一個XMLHttpRequest發送數據到PHP後端。訪問XMLHttpRequests在PHP後端發送(數據)

var req = new XMLHttpRequest(); 
req.open('GET', url); 

req.onload = function() { 
    // This is called even on 404 etc 
    // so check the status 
    if (req.status == 200) { 
    // Resolve the promise with the response text 
    resolve(req.response); 
    } 
    else { 
    // Otherwise reject with the status text 
    // which will hopefully be a meaningful error 
    reject(Error(req.statusText)); 
    } 
}; 

// Handle network errors 
req.onerror = function() { 
    reject(Error("Network Error")); 
}; 

// Make the request 
req.send('query=messages'); // <-- i want to access this in php 

我想 print_r($_GET)print_r($_REQUEST)但既不工程。

任何人都知道如何訪問這些數據?

+0

你看了在瀏覽器的控制檯中的請求/響應? –

+0

是@JayBlanchard它似乎並沒有在所有提供查詢=消息: GET /rest/api.php HTTP/1.1 主機:本地主機連接 :保持活躍 產地:HTTP://本地主機:8000 User-Agent:Mozilla/5.0(Windows NT 6.1; WOW64)AppleWebKit/537.36(KHTML,如Gecko)Chrome/47.0.2526.111 Safari/537.36 接受:*/* 引用者:http:// localhost:8000/index。 html Accept-Encoding:gzip,deflate,sdch Accept-Language:de-DE,de; q = 0.8,en-US; q = 0.6,en; q = 0.4 –

+0

請參閱下面的答案。 –

回答

2

您只能通過XMLHttpRequest.send()-方法發送POST請求的數據,而不是GET。

對於GET請求,您需要將數據追加到URL作爲查詢字符串。

url += "?query=message"; 

然後你就可以使用檢索與PHP的數據:

$message = $_GET['query']; 

更多信息:http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

+0

aaah好吧,我不知道。使用XMLHttpRequest來調用一個PHP REST API似乎有點不方便,因爲我必須使用URL來獲取併發送POST()。在香草js中有更好的方法嗎? –

+0

不是。我會爲它製作一個小包裝,並使用它:'ajax.get(url,data,callback);'''和'ajax.post(url,data,callback)'並在這些方法中處理請求。 –