我试图在Javascript(不使用jquery)中通过AJAX进行HTTP POST
ajax_post = function(aData) {
var k, v, xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", aData.path, true);
xmlhttp.setRequestHeader('Content-Type', 'application/json');
xmlhttp.send(JSON.stringify(aData));
return xmlhttp.responseText;
};
服务器端正在获取POST并正在发送响应。我知道响应正在响应客户端,因为我使用http://code.google.com/p/chrome-rest-client/
测试了服务器,并且它响应了服务器按预期发送的JSON。
我将整个XMLHttpRequest
对象转储到控制台,但仍然看不到我错过的内容:
statusText
status 0
response
responseType
responseXML null
responseText
upload
XMLHttpRequestUpload {ontimeout: null, onprogress: null, onloadstart: null, onloadend: null, onload: null…}
withCredentials false
readyState 1
timeout 0
onreadystatechange null
ontimeout null
onprogress null
onloadstart null
onloadend null
onload null
onerror null
onabort null
open function open() { [native code] }
setRequestHeader function setRequestHeader() { [native code] }
send function send() { [native code] }
abort function abort() { [native code] }
getAllResponseHeaders function getAllResponseHeaders() { [native code] }
getResponseHeader function getResponseHeader() { [native code] }
overrideMimeType function overrideMimeType() { [native code] }
UNSENT 0
OPENED 1
HEADERS_RECEIVED 2
LOADING 3
DONE 4
addEventListener function addEventListener() { [native code] }
removeEventListener function removeEventListener() { [native code] }
dispatchEvent function dispatchEvent() { [native code] }
我的客户端POST请求有什么问题?
答案 0 :(得分:0)
我想出来了
ajax_post = function(aData, aCB) {
var xmlhttp;
xmlhttp = void 0;
// Fallback for IE5/6
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// Send Request to Server
xmlhttp.open("POST", aData.path, true);
// Set Header Information specifying what type of data you are sending
xmlhttp.setRequestHeader('Content-Type', 'application/json');
// Callback that waits untill request is finished and responce is ready
xmlhttp.onreadystatechange = (function(_this) {
return function() {
// readyState
// - 0: request not initialized
// - 1: server connection established
// - 2: request received
// - 3: processing request
// - 4: request finished and response is ready
// status
// - 200: OK
if ((aCB != null) && xmlhttp.readyState === 4 && xmlhttp.status === 200) {
aCB(xmlhttp.responseText);
}
// TODO check for xmlhttp.status !== 200 Because error handeling should be done
};
})(this);
// Sends Request Request Payload
xmlhttp.send(JSON.stringify(aData));
};
编辑:为每个请求添加评论