![](/img/trans.png)
[英]Using gettext with Javascript from PHP via XMLHttpRequest
[英]Sending data from JavaScript to PHP via XMLHttpRequest
美好的一天。
我正在尝试将一个简单的数据从一个php文件(manage.php)发送到另一个(view.php)。
我无法通过表单发送数据,我想通过JS脚本发送数据。 这是我的尝试:
var read = function(id) { xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST", "view.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("id=" + id); }
在view.php中,使用$ _POST [“ id”]会导致错误,指出未定义索引“ id”。
发送数据的正确方法是什么? 谢谢。
您的输入不完整。 因此,我在下面做了一个完整的示例,您可以遵循。 我创建了一个名为readid(id)的函数,可以根据需要执行相同的操作。 然后,在需要时,我从html调用该函数。
<!doctype html>
<html lang="fr">
<head>
<meta charset="iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript" charset="iso-8859-1">
function readid(id){
"use strict";
console.log("id=", id)
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/cgi-bin/view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 || this.status === 200){
console.log(this.responseText); // echo from php
}
};
xmlhttp.send("id=" + id);
}
</script>
</head>
<body>
<p>This is a test</p>
<input type="button" name="Submit" value="Submit" id="formsubmit" onClick="readid(id)">
</body>
</html>
view.php
<?php
$logFile = "view.log";
$id = $_POST['id'];
file_put_contents($logFile, $id);
echo $id;
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
$.ajax({
type: 'POST',
data: id,
url: 'PATH_TO_VIEW.PHP',
success: function(data) {
//do something
},
error: function(data){
console.log('Something went wrong.');
}
});
});
</script>
</body>
</html>
现在,可以收集大量ajax中的数据,例如序列化的和新的FormData(form)以快速命名为两个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.