Post data ajax from file local to server in pure javascript

不问归期 提交于 2019-12-25 04:11:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!