[英]How to add Header Authorization for POST FORM using JS/AJAX/JQUERY?
我想使用頁面上的表單獲取輸入並將這些值提交到托管在另一個外部站點上的 php。 請求制造商擴展顯示了在外部站點上提交數據時與其他輸入一起傳遞的標頭授權。
結果可能是一個xml文件(Student Record)。需要拉出來作為結果顯示。
嘗試了很多使用 $.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) { xhr.setRequestHeader('Authorization', "Basic XXXXXXXXXXXXXXXXXXXXXXXXX" ); or xhr.setRequestHeader('Authorization', "Basic " +btoa(ser_user + ':' + ser_pass)); }, 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" > Enter Your Name<br> <input type="text" name="name" > <br> <input type="submit" onclick="myFunction()" value="Submit"> </body>
將值從我的頁面提交到外部 php 時,如何添加此標頭授權? 請幫忙 !
它有點晚了,但仍然為可能面臨同樣問題的未來讀者發布答案。 當在 ajax 請求中明確提及時,請不要在 html 代碼中提供表單提交 url(操作)和方法類型(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 服務結果.php
<?php
print_r($_POST["keyName"]);
?>
我有一個類似的問題,需要在HTTP
POST
請求標頭中添加身份驗證標頭名稱和身份驗證令牌值。 在構成 HTML 面板的其中一個 JSP 中添加了此 javascript 攔截器功能,該面板是 Web 應用程序中每個頁面的一部分。
// this will add employee authentication headers to every ajax call
(function() {
var site = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
this.setRequestHeader("${employee.role.header}", "${employee.auth.secret}")
return site.apply(this, [].slice.call(arguments));
};
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.