0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

素のJavaScriptのみでのAjax共通ロジック

Last updated at Posted at 2019-11-30

最近はjQuery使いたくない時もあるので、これもメモ

commonajax.js
//-----------------------------------------------
// 素のJavaScriptのみでのAjax共通ロジック
// @param url   リクエスト先
// @param requestJson リクエストデータ(json形式)
// @param callback 取得後実行処理
// @param cbparam 取得後実行処理に対する引数
//-----------------------------------------------
const commonajax = function(url, requestjson, callback, cbparam){

    fetch(url,{
        method : "POST",
        body : JSON.stringify(requestJson),
        headers: {"Content-Type": "application/json; charset=utf-8"},
    })
    .then(function(res){
        return res.json(); 
    })
    .then(function(data){
        // 返されたデータ(json) 
        if(callback) callback(data, cbparam);
    })
    .catch(function(err){
        // エラー処理
        console.error(err);
    });
}

使い方

{"reqname1":"name1","reqname2":"name2"} 

みたいなjsonが帰ってくるとして

temp.js
window.addEventListener("load", function(){
    //イベントトリガー
    var getbtn = document.getElementById("getbtn");
    if(getbtn){
        //クリックしたとき
        getbtn.addEventListener("click", function(){
            commonajax("hoge/ajax",
            {reqcode:"001"}
            setdata,
            {setid1:"field1",setid2:"field2"});
        });
        
        //事後処理
        var setdata = function(data, param){
        	console.log(data)
        	var elem1 = document.getElementById(params["setid1"]);
        	if(elem1) elem1.value = data["reqname1"];
        	var elem2 = document.getElementById(params["setid2"]);
        	if(elem2) elem2.value = data["reqname2"];
        }            
    }    
});

使い方の動作確認はまだしてない(^^;

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?