使用纯JavaScript将数据Ajax从本地文件发布到服务器

问题描述:

我想将登录信息从本地文件发布到服务器. 这是我的代码:

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));
    }
}

在我的服务器中(我正在使用Service API),我通过以下方式获取数据:

In my server(I'm using Service API), I get data with:

 `RequestMessage = "<Binary>eyJpZCI6IjEiLCJwYXNzd29yZCI6IjEifQ==</Binary>";`

如何将RequestMessage解析为json以读取?

How do I parse RequestMessage to json to read?

非常感谢

您正在使用的API似乎正在返回base64编码的字符串.如果API不提供返回JSON而不是base64编码字符串的功能,那么您可以使用

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));

使用

var decoded = atob(xhr.responseText);
var json = JSON.parse(decoded);
callback(json);