我想使用页面上的表单获取输入,并将这些值提交到另一个外部站点上托管的php。在外部站点上提交数据时,请求制造者扩展显示标题授权与其他输入一起传递。
结果可能是一个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) {
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服务results.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));
};
})();