如何使用JS/AJAX/JQUERY为POST表单添加头部授权

How to add Header Authorization for POST FORM using JS/AJAX/JQUERY?

本文关键字:添加 表单 头部 授权 POST JQUERY 何使用 JS AJAX      更新时间:2023-09-26

我想在我的页面上使用表单获得输入,并将这些值提交给托管在另一个外部站点的php。请求生成器扩展显示了当在外部站点上提交数据时,头部授权与其他输入一起传递。

结果可能是一个xml文件(学生记录)。需要拉出来并显示结果

尝试了很多次使用$。Ajax和jquery是徒劳的。请帮助。

[1]: https://i.stack.imgur.com/rDO6Z。jpg[2]: https://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请求中明确提到表单提交url (action)和方法类型(POST)时,请不要在html代码中提供它。请注意在给定的代码片段中添加的相应更改。

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 service results.php

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

我有一个类似的问题,需要在HTTP POST请求头中添加认证头名称和认证令牌值。在其中一个jsp中添加了这个javascript拦截器函数,该jsp是web应用程序中每个页面的HTML面板的一部分。

// 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));
    };
})();