18
19

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.

XMLHttpRequestでJSONをPOST

Last updated at Posted at 2018-06-18

#はじめに
JSONのデータをサーバーに送って処理するのにXMLHttpRequestでPOSTしてサーブレットで受け取ります。

#XMLHttpRequestでPOST
ブラウザの右クリックメニューで post json した時にデータをPOSTします。

  • POSTする文字列は POST.stringify(object or array) する。
  • POSTするときのヘッダーは xhr.setRequestHeader("Content-Type", "application/json")
  • xhr.send(string) で送信
background.js
browser.contextMenus.create({
    id: "name",
    title: "get name",
    contexts: ["selection"]
});

browser.contextMenus.create({
	id: "postJson",
	title: "post json",
	contexts: ["all"]
});

name = "blue";
browser.contextMenus.onShown.addListener(info => {
	getting = browser.storage.local.get("name", function (value) {
	    name = value.name;
	    console.log("getting " + name);
	});
});

browser.contextMenus.onClicked.addListener((info, tab) => {
    if (info.menuItemId === "name" ){
        console.log(name);
    } else if (info.menuItemId === "select text") {
    	let persons = [];
    	let person1 = new Object();
    	person1.name = "Satoh Taro";
    	person1.id = "123";
    	person1.mail = "taro@sample.com";
    	persons.push(person1);
    	let person2 = new Object();
    	person2.name = "Suzuki Hana";
    	person2.id = "124";
    	person2.mail = "hana@sample.com";
    	persons.push(person2);
    	let json = JSON.stringify(persons);
        console.log(json);
        var url = "http://localhost:9080/sampleWeb/TestServlet";
        console.log("start doPost");
        doPost(url, json);
        console.log("end doPost");
    }
});

function doPost(url, data) {
   console.log(url);
   var xhr = new XMLHttpRequest();
   xhr.open("POST", url);
   xhr.setRequestHeader("Content-Type", "application/json");
   xhr.onload = () => {
     console.log(xhr.status);
     console.log("success!");
   };
   xhr.onerror = () => {
     console.log(xhr.status);
     console.log("error!");
   };
   xhr.send(data);
}

image.png

このコードだけでうまくいくと思ったのですが、 xhr.statusの戻り値が 0 になってて動いてない、TCPモニターもとってみたのですがサーバーまでリクエストが来ていないような状況でした。

image.png

しばらく試行錯誤して "permissions" に "http:///" が必要だったことがわかりました。

manifest.json
{
	"manifest_version": 2,
	"name": "Sample Tool",
	"description": "Sample Tool for Firefox",
	"version": "1.0",
	"homepage_url": "https://sample.com",
	"icons": {
		"48": "icons/sample.png"
	},
	"applications": {
		"gecko": {
			"id": "sample@sample.com",
			"strict_min_version": "42.0", 
			"update_url":"https://sample.com/"
		}
	},
	"background": {
		"scripts": [
			"background.js"
		]
	},
	"options_ui": {
    	"page": "options.html"
    },
	"permissions": [
		"contextMenus",
		"storage",
		"http://*/*"
	],
	"content_scripts": [
		{
			"matches": [
				"https://qiita.com/keniooi/*"
			],
			"js": [
				"sample.js"
			]
		}
	]
}

200が戻ってくるようになりました。
image.png

#参考
menus.ContextType

18
19
2

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
18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?