问题
I want to post info of login from file local to server. This is my code:
var UrlDetails = 'http://xxx.xxx.x.xxx:xxxx';
function createCORSRequest(method, url, asynch) {
// Create the XHR object.
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
//if (method == 'POST') {
// xhr.setRequestHeader('Content-Type', 'application/json');
//}
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url, asynch);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
function postDoLogin(e, callback) {
var url = UrlDetails + '/api/login?f=json';
var xhr = createCORSRequest('POST', url, true);
if (xhr) {
xhr.onreadystatechange = function () {
try {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
xhr.status === 403 ? modalShow() : errorServer(xhr.status);
}
}
}
catch (e) {
alert('Caught Exception: ' + e.description);
}
};
xhr.send(JSON.stringify(e));
}
}
In my server(I'm using Service API), I get data with:
`RequestMessage = "<Binary>eyJpZCI6IjEiLCJwYXNzd29yZCI6IjEifQ==</Binary>";`
How do I parse RequestMessage to json to read?
Thank you very much
回答1:
It looks like the API you are using is returning base64 encoded string. If the API does not provide a feature to return JSON instead of base64 encoded string, then you can simply decode it in JavaScript using atob().
So in your code instead of
callback(JSON.parse(xhr.responseText));
Use
var decoded = atob(xhr.responseText);
var json = JSON.parse(decoded);
callback(json);
来源:https://stackoverflow.com/questions/40885192/post-data-ajax-from-file-local-to-server-in-pure-javascript