XHR Post用于保存document.body JS

时间:2017-06-21 21:28:48

标签: javascript post xmlhttprequest

我需要将document.body.innerHTML发布到我的域代理。有工作的PM2,在它使用GET之前它看起来像:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://domain.ru/pmproxy?info='+document.body.innerHTML+'&location='+document.location+1);
xhr.send();

现在,因为我需要POST的信件数量有限。我该怎么把它变成POST?

2 个答案:

答案 0 :(得分:0)

首先确保接收服务器方法接受帖子,如果你想在xhr帖子中发送数据,你可以这样做

xhr.send("info='+document.body.innerHTML+'&location='+document.location+1")

或者如果服务器接受json对象,那么您可以使用xhr.send(document.getElementById('#form).serialize());

答案 1 :(得分:-1)

您应该将其转换为:

var xhr = new XMLHttpRequest();
xhr.open('post', 'https://domain.ru/pmproxy');
xhr.send('info='+document.body.innerHTML+'&location='+document.location+1);

另外,我建议你清理这两个参数,以免将来出现问题:

xhr.send('info='+encodeURIComponent(document.body.innerHTML)+'&location='+encodeURIComponent(document.location+1));

此外,我并不知道你为什么要使用document.location + 1,但是你可以使用document.location.href并保存+1,这样你的代码看起来更干净:

xhr.send('info='+encodeURIComponent(document.body.innerHTML)+'&location='+encodeURIComponent(document.location.href));