使用 JavaScript 将 HTTP POST 请求连接到 onclick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20307590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:12:08  来源:igfitidea点击:

Connect HTTP POST request to an onclick using JavaScript

javascripthtml

提问by NicoM

I am trying to make an HTTP POST request using javascript and connecting it to an onclick event.

我正在尝试使用 javascript 发出 HTTP POST 请求并将其连接到 onclick 事件。

For example, if someone clicks on a button then make a HTTP POST request to http://www.example.com/?test=test1&test2=test2. It just needs to hit the url and can close the connection.

例如,如果有人单击按钮,则向 发出 HTTP POST 请求http://www.example.com/?test=test1&test2=test2。它只需要点击 url 就可以关闭连接。

I've messed around in python and got this to work.

我在 python 中搞砸了,让它工作。

import urllib2
def hitURL():
    urllib2.urlopen("http://www.example.com/?test=test1&test2=test2").close

hitURL()

I have read about some ways to make HTTP requests using JavaScript in this thread JavaScript post request like a form submit, but think it's overkill for what I need to do.

我已经在这个线程中阅读了一些使用 JavaScript 发出 HTTP 请求的方法 JavaScript post request like a form submit,但认为这对于我需要做的事情来说太过分了。

Is it possible to just say something like this:

是否可以只说这样的话:

<button onclick=POST(http://www.example.com/?test=test1&test2=test2)>hello</button>
Or build it in to an event listener. 

I know that is not anything real but I am just looking for a simple solution that non-technical people can use, follow directions, and implement.

我知道这不是真的,但我只是在寻找一个简单的解决方案,非技术人员可以使用、遵循指示并实施。

I honestly doubt there is something that simple out there but still any recommendations would be appreciated.

老实说,我怀疑那里有什么简单的东西,但仍然会感谢任何建议。

回答by Hardmath123

You need to use XMLHttpRequest(see MDN).

您需要使用XMLHttpRequest(参见MDN)。

var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.onload = // something
document.getElementById("your_button's_ID").addEventListener("click",
    function() {xhr.send(data)},
    false
);

回答by Ryan Nigro

If you can include the JQuery library, then I'd suggest you look in to the jQuery .ajax() method (http://api.jquery.com/jQuery.ajax/):

如果您可以包含 JQuery 库,那么我建议您查看 jQuery .ajax() 方法(http://api.jquery.com/jQuery.ajax/):

$.ajax("http://www.example.com/", {
    type: 'POST',
    data: {
      test: 'test1',
      test2: 'test2'
    }
  })