.NET 開発基盤部会 Wiki」は、「Open棟梁Project」,「OSSコンソーシアム .NET開発基盤部会」によって運営されています。

目次

概要

JavaScript の HTTP Client も色々ある。

#非同期呼出の実現方式外部のパッケージ(便利)組込み(基礎的)
1コールバックjQueryxhr
2Promiseaxiosfetch

fetch (Fetch API)

サンプル

クロスドメイン

参考

axios

サンプル

...。

クロスドメイン

  • 以下を見ると、クライアント側は特に何もしなくて良さそう。

参考

jQuery.ajax()

HTTPリクエストを使用してデータを取得するajax の最も低レベルな実装。

以下の様なメソッドも存在する。

  • jQuery.get()
  • jQuery.post()

サンプル

POST

以下のjQuery.ajaxによるPOSTのサンプル・スニペットを使用すれば色々なパターンを処理可能。

$('#btnTest').click(function () {
    $.ajax({
        type: 'post',
        url: 'http://・・・',
        crossDomain: true,
        contentType: 'application/x-www-form-urlencoded',
        headers: {
            'Authorization': 'Bearer ' + token
        },
        data: {
            client_id: '・・・',
            client_secret: '・・・',
        },
        xhrFields: {
            withCredentials: true
        },
        success: function (responseData, textStatus, jqXHR) {
            alert(textStatus + ', ' + responseData);
        },
        error: function (responseData, textStatus, errorThrown) {
            alert(textStatus + ', ' + errorThrown.message);
        }
    });
});

GET

上記を、GETもイケるよう、改造した。

urlに'get'を、postdataにはnullを指定する。

function CallOAuthAPI(url, httpMethod, postdata) {
    $.ajax({
        type: httpMethod,
        url: url,
        crossDomain: true,
        headers: {
            'Authorization': 'Bearer ' + token
        },
        data: postdata,
        xhrFields: {
            withCredentials: true
        },
        success: function (responseData, textStatus, jqXHR) {
            alert(textStatus + ', ' + responseData);
        },
        error: function (responseData, textStatus, errorThrown) {
            alert(textStatus + ', ' + errorThrown.message);
        }
    });
}

JSON

以下は、Web Storageからkey, valueをJSONでPOSTする例。
JSON文字列へのデシリアライズ処理にはJSON.stringify()?を使用する

// ---------------------------------------------------------------
// Web Storageからkey, valueをJSONでPOSTする。
// ---------------------------------------------------------------
// 引数    url : POST先のURL
// 戻り値  -
// ---------------------------------------------------------------
function PostJsonWebStorage(url) {
    // Web Storageのすべての情報の取得
    var jsonArray = new Array();

    for (var i = 0; i < storage.length; i++) {
        var _key = storage.key(i);

        // Web Storageのキーと値を表示
        var jsonBean = {
            key: _key,
            value: storage.getItem(_key)
        };

        jsonArray.push(jsonBean);
    }

    // <p id="url"></p> に表示
    if (document.getElementById("url") != null) {
        $("#url").text(url);
    }
    // <p id="request"></p> に表示
    if (document.getElementById("request") != null) {
        $("#request").text("request:" + JSON.stringify(jsonArray).toString());
    }

    CallService("POST", url, JSON.stringify(jsonArray), "application/json; charset=utf-8", "JSON", false);
}

// ---------------------------------------------------------------
// ajax
// ---------------------------------------------------------------
// 引数
//         Type : GET or POST or PUT or DELETE verb
//         Url : Location of the service
//         Data : Data sent to server
//         ContentType : Content type sent to server
//         DataType : Expected data format from server
//         ProcessData : True or False
// 戻り値  -
// ---------------------------------------------------------------
function CallService(Type, Url, Data, ContentType, DataType, ProcessData) {
    $.ajax({
        type: Type,
        url: Url,
        data: Data,
        cache: false,
        contentType: ContentType,
        dataType: DataType,
        processdata: ProcessData,
        success: function (data) {
            // On Successfull service call
            ServiceSucceeded(data);
        },
        error: function (data) {
            // When Service call fails
            ServiceFailed(data);
        }
    });
}

クロスドメイン

  • crossDomain: trueを追加する。
  • 下位がxhr (XMLHttpRequest)なので
    • XDomainRequest?等の切り替えは自動的に行われる。
    • 対応したカスタムヘッダ設定が必要なこともある。
  • 参考

contentTypeとdataTypeの違い

contentType

  • サーバにデータを送信する際に用いるcontent-typeヘッダの値
  • 既定値は"application/x-www-form-urlencoded"。
  • JSONを送信する場合は"application/json"とする。

dataType

  • サーバから返されるデータの型を指定する。
  • 既定値ではjQueryがMIMEタイプなどを見ながら自動的に判別。
  • JSONを受信する場合は"json"とすると、JavaScriptのオブジェクトに変換される。

参考

  • javascript - Differences between contentType and dataType in jQuery ajax function - Stack Overflow
    Differences between contentType and dataType in jQuery ajax function

xhr (XMLHttpRequest?)

  • Ajaxの基幹技術。
  • JavaScriptなどのブラウザ上のスクリプト言語から
    HTTP通信を行うための、組み込みオブジェクト(API)。

サンプル

...。

クロスドメイン

  • IE8, 9では XMLHttpRequest? の代わりに XDomainRequest? を使う
  • (X-Requested-Withのような)カスタムヘッダを付けるとGETリクエストでもプリフライトする。

参考

参考

クロスドメイン


トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2021-05-21 (金) 15:39:35 (1064d)