下のようなエラーが出ました。
Uncaught DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED. at outputForm (http://localhost:8888/wp/wp-admin/admin.php?page=test-plugin:322:9) at HTMLButtonElement.onclick (http://localhost:8888/wp/wp-admin/admin.php?page=test-plugin:191:147)
実装しているコードは下のようなコードです。
// 作成したフォームを出力する function outputForm() { let dom = document.getElementById("result"); if (dom == null || typeof dom == 'undefined') { alert("Error"); return; } let question = document.getElementById("question").innerText; let inputs = dom.getElementsByTagName("button"); let ansArray = []; for (let i = 0; i < inputs.length; i++) { ansArray.push(inputs[i].innerText); } // 送信するデータ(リクエストパラメータ) let data = createSendData(question, ansArray); // DBへデータの登録(汎用的に作成したメソッドなので後ろの引数は全てnullにしている) // 下のメソッドは次のように書いても良い(JSの場合) => createXHR("POST", stateChangeMethod); let xhr = createXHR(stateChangeMethod, null, null); // JSONで送信する xhr.setRequestHeader("Content-Type", "application/json"); xhr.open("POST", ''); xhr.send(data); } function createSendData(question, ansArray) { let obj = {}; obj.question = question; for (let i = 0; i < ansArray.length; i++) { obj["ans" + i] = ansArray[i]; } return obj; } /* * XMLHttpRequest生成のメソッド * @param stateChangeMethod レスポンスを取得する時の処理 * @param btnId 謳歌したときに起動するボタンのID * @param clickMethod ボタンのクリック時の処理 */ function createXHR(stateChangeMethod, btnId, clickMethod) { xhr = new XMLHttpRequest(); if (btnId != null && typeof btnId == "undefined") { document.getElementById(btnId).addEventListener('click', clickMethod); } xhr.onreadystatechange = stateChangeMethod; return xhr; }
エラーメッセージから「XMLHttpRequestをOPENしてからコンテントタイプなどを指定してね!」と言っているので
そのようにします。
// JSONで送信する xhr.open("POST", ''); xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(data);
そしたら解決しました(笑)