2015-10-02 31 views
3

我想使用我的網頁上的表單獲得輸入,並將這些值提交給另一個外部網站上託管的PHP。請求製作者擴展程序顯示在外部網站上提交數據時,標題授權與其他輸入一起傳遞。如何使用JS/AJAX/JQUERY爲POST FORM添加標題授權?

結果可能是一個xml文件(學生記錄)。需要將其拉出並顯示爲結果。

嘗試了很多使用$ .Ajax和jquery的徒勞。請幫忙。

[1]:http://i.stack.imgur.com/rDO6Z。 jpg [2]:http://i.stack.imgur.com/92uTh。 JPG

function myFunction() { 
 
var name = document.getElementById("name").value; 
 

 
// AJAX code to submit form. 
 
$.ajax({ 
 
type: "POST", 
 
url: "http://externalsite.cpm/results.php.php", 
 
data: dataString, 
 
    beforeSend: function(xhr) { 
 
\t 
 
    xhr.setRequestHeader('Authorization', "Basic XXXXXXXXXXXXXXXXXXXXXXXXX"); or xhr.setRequestHeader('Authorization', "Basic " +btoa(ser_user + ':' + ser_pass)); 
 
\t \t \t \t \t \t }, 
 
cache: false, 
 
success: ??? 
 

 

 
xmlhttp.open("POST","your_url.php",true); 
 
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
 
xmlhttp.send("name=" + name + "&email=" + email);
<body> 
 

 
<form action="http://externalsite.cpm/results.php" method="post" > 
 
\t Enter Your Name<br> 
 
\t <input type="text" name="name" > 
 
\t <br> 
 
\t <input type="submit" onclick="myFunction()" value="Submit"> 
 
\t 
 
</body>

從我的頁面提交值外部PHP時我如何添加這個頭授權?請幫忙 !

回答

3

它有點晚了,但仍然爲未來可能面臨同樣問題的讀者發佈答案。 當在ajax請求中明確提到時,請不要在html代碼中提供表單提交網址(操作)和方法類型(POST)。 注意給出的代碼片段中添加的相應更改。

HTML表單代碼:

  <form><!---Removed form submit url--> 
      <input type="text" id="keyName" value="testValue"> 
      <!---Id attribute added to input field to be submitted---> 
      <input type="button" onclick="myFunction()" value="Submit"> 
      <!---Input type is button NOT submit---> 
      </form> 

Javascript代碼:

function myFunction(){ 
var dataValue = $("#keyName").val(); 
$.ajax({ 
      type : 'POST', 
      //remove the .php from results.php.php 
      url : "http://externalsite.cpm/results.php", 
      //Add the request header 
      headers : { 
       Authorization : 'Bearer ' + 'XXXXXXXXXXXXXXXXXXXXXXXXX' 
      }, 
      contentType : 'application/x-www-form-urlencoded', 
      //Add form data 
      data : {keyName : dataValue}, 
      success : function(response) { 
       console.log(response); 
      }, 
      error : function(xhr, status, error) { 
       var err = eval("(" + xhr.responseText + ")"); 
       console.log(err);     
      } 
     }); //End of Ajax 
} // End of myFucntion 

更新:

PHP服務results.php

<?php 
    print_r($_POST["keyName"]); 
?> 
+0

感謝您的回覆。我嘗試過,但點擊提交沒有任何反應。如果你能設置一個可用的jsfiddle,我將非常感激。提前致謝。 –

+0

更新了帖子。在這種情況下,您將不得不託管php服務。按F12在您的網頁上,然後打開控制檯查看響應記錄器。 – Daenarys

+0

幾乎在那裏。在提交時,我在控制檯中得到以下響應 XMLHttpRequest無法加載http://externalsite.com/results.php \t。對預檢請求的響應未通過訪問控制檢查:「Access-Control-Allow-Origin」標頭的值爲'http://subdomain.externalsite.com',它不等於提供的原點。因此不允許原產地'null'訪問。 但是使用名爲「Access-Control-Allow-Origin(CORS)」的擴展名爲「 」我能夠成功提交併獲得所需的結果。 –