我需要一些帮助。我想登录www.mywebsite.com/login.html并保留cookie以便在我提交旅行表格时使用,因为您需要先提交,然后才能提交表格。
当我尝试点击“登录”按钮时,没有发生任何事情。
以下是我的代码和表单截图。
<!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>
答案 0 :(得分:0)
代码本身似乎是正确的(创建了click事件),但有些网站会阻止这些请求并抛出“跨域请求被阻止”。
如果您从www.mywebsite1.com/test.html致电www.mywebsite2.com,就会发生这种情况
我尝试过多个网站,包括www.google.com:
$.post("http://www.google.com",
如果您希望启用CORS,则必须在目标服务器上执行此操作:https://enable-cors.org - 但是,对于某些管理员,这将存在安全风险。
答案 1 :(得分:0)
在我谈到答案之前,了解表单按钮必须有ID是很重要的。稍后当您尝试定位该元素时,这会很有用。这是一个例子
<button id="SendMyStatus">
Send an HTTP POST request to a page and get the result back
</button>
$("button").click(function(){ ... }
或者您可以使用onClick
按钮事件。
<button onClick="SendMyStatus()"></button>
<script> function SendMyStatus(){ ... }</script>