我在前端后端交互方面遇到了麻烦。我相对确定我正在发送数据,但之后我无法访问数据。最近我使用了这个代码模板(来自 mozilla 的帮助页面的链接 )来发送数据。JavaScript:
function sendData(data) {
var XHR = new XMLHttpRequest();
var urlEncodedData = "";
// We turn the data object into a URL encoded string
for(name in data) {
urlEncodedData += name + "=" + data[name] + "&";
}
// We remove the last "&" character
urlEncodedData = urlEncodedData.slice(0, -1);
// We URLEncode the string
urlEncodedData = encodeURIComponent(urlEncodedData);
// encodeURIComponent encode a little to much things
// to properly handle HTTP POST requests.
urlEncodedData = urlEncodedData.replace('%20','+').replace('%3D','=');
// We define what will happen if the data are successfully sent
XHR.addEventListener('load', function(event) {
alert('Yeah! Data sent and response loaded.');
});
// We define what will happen in case of error
XHR.addEventListener('error', function(event) {
alert('Oups! Something goes wrong.');
});
// We setup our request
XHR.open('POST', 'http://ucommbieber.unl.edu/CORS/cors.php');
// We add the required HTTP header to handle a form data POST request
XHR.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
XHR.setRequestHeader('Content-Length', urlEncodedData.length);
// And finally, We send our data.
XHR.send(urlEncodedData);
}
HTML:
<button type="button" onclick="sendData({test:'ok'})">Click Me!</button>
我的问题是:是否有更好的数据发送方式(更适合节点)?以及如何访问服务器端的数据?