简体   繁体   English

jQuery / AJAX-如何通过XMLHTTPRequest发布数据/登录到网站

[英]jQuery / AJAX - How to post data / login to a web site via XMLHTTPRequest

I need some help. 我需要协助。 I'd like login to www.mywebsite.com/login.html and keep the cookies in order to be used when I submit the travel form because you need to login first before you can submit the form. 我想登录www.mywebsite.com/login.html并保留cookie以便在我提交旅行表格时使用,因为您需要先登录才能提交表格。

Nothing is happening when I try to click on "Login" button. 当我尝试单击“登录”按钮时,没有任何反应。

Below is my code and the screenshot of the form. 下面是我的代码和表单的屏幕截图。

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $.post("https://www.mywebsite.com/login.html", { login: "alice007@gmail.com", password: "alice1995" }, function(data,status){ alert("Data: " + data + "\\nStatus: " + status); }); }); }); </script> </head> <body> <button>Send an HTTP POST request to a page and get the result back</button> </body> </html> 

screenshot of Login Form 登录表单的屏幕截图

The code itself seems to be correct (click event is created), but some sites block these requests and throw "Cross-origin request blocked". 代码本身似乎是正确的(创建了click事件),但是某些站点阻止了这些请求并抛出了“跨源请求被阻止”。

That will occur if you call this from www.mywebsite1.com/test.html to www.mywebsite2.com 如果您将其从www.mywebsite1.com/test.html调用到www.mywebsite2.com,则会发生这种情况

I have tried for multiple sites including for www.google.com: 我已经尝试过多个网站,包括www.google.com:

$.post("http://www.google.com",

See this image for more details what happened after button click: 有关更多详细信息,请参见此图像,单击按钮后会发生什么: Firefox-开发人员工具

If you wish to enable CORS, you have to do that on the target server: https://enable-cors.org - but, for some admins it will be a security risk. 如果要启用CORS,则必须在目标服务器上执行此操作: https : //enable-cors.org-但是,对于某些管理员来说,这将带来安全风险。

Before I talk about the answer, it's important to know that the form button must have an ID. 在讨论答案之前,务必要知道表单按钮必须具有ID。 This is helpful later when you're trying to target that element. 稍后在尝试定位该元素时,这将很有帮助。 Here's an example 这是一个例子

<button id="SendMyStatus">
  Send an HTTP POST request to a page and get the result back
</button>
$("button").click(function(){ ... }

or you can use onClick event of button. 或者您可以使用按钮的onClick事件。

<button onClick="SendMyStatus()"></button>

<script> function SendMyStatus(){ ... }</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM