简体   繁体   中英

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.

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".

That will occur if you call this from www.mywebsite1.com/test.html to www.mywebsite2.com

I have tried for multiple sites including for 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.

Before I talk about the answer, it's important to know that the form button must have an 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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