2017-05-02 121 views
0

我需要一些幫助。我希望登錄www.mywebsite.com/login.html並保存cookies以便在我提交旅行表格時使用,因爲您需要先登錄才能提交表格。jQuery/AJAX - 如何通過XMLHTTPRequest發佈數據/登錄到網站

當我嘗試點擊「登錄」按鈕時沒有任何事情發生。

下面是我的代碼和窗體的截圖。

<!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: "[email protected]", 
 
      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

+0

您需要PHP來設置cookie和會話登錄。 – Oen44

+0

@ Oen44提出了一個很好的問題。你如何設置cookie? –

回答

0

代碼本身似乎是正確的(點擊創建事件),但一些網站阻止這些請求,並拋出「跨域請求封殺」。

,如果從www.mywebsite1.com/test.html稱這www.mywebsite2.com

我已經嘗試了多個網站,包括瀏覽www.google.com會發生:

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

看到該圖片的更多詳細信息按鈕,點擊之後發生了什麼:Firefox - Developer Tools

如果要啓用CORS,你所要做的是在目標服務器上:https://enable-cors.org - 但是,對於一些管理員這將是一個安全隱患。

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> 
+0

@Garrett kadillak感謝編輯的話。我猜,我不懂英語 –