我想使用我页面上的表单获取输入,并将这些值提交到另一个外部站点上托管的 php。请求制造商扩展显示在外部站点上提交数据时, header 授权与其他输入一起传递。
结果可能是一个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 提交值时如何添加此 header 授权?请帮忙!
最佳答案
它有点晚了,但仍然为可能面临相同问题的 future 读者发布答案。 当在 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"]);
?>
关于javascript - 如何使用 JS/AJAX/JQUERY 为 POST FORM 添加 Header Authorization?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32901015/