簡體   English   中英

使用純JavaScript將數據Ajax從本地文件發布到服務器

[英]Post data ajax from file local to server in pure javascript

我想將登錄信息從本地文件發布到服務器。 這是我的代碼:

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)中,我通過以下方式獲取數據:

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

如何將RequestMessage解析為json以讀取?

非常感謝你

您正在使用的API似乎正在返回base64編碼的字符串。 如果API不提供返回JSON而不是base64編碼的字符串的功能,那么您可以使用atob()在JavaScript中對其進行解碼。

所以在你的代碼而不是

callback(JSON.parse(xhr.responseText));

采用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM