我是网络开发的新手,尤其是PHP,jQuery,AJAX ......
我正在尝试让用户输入名称,然后index.html将其发送到php文件,php文件将其保存到名称文件中,并在网站上更改id为status的div元素。 我无法弄清楚问题,div元素的内部HTML保持“处理......”
的index.html
.htaccess
server.php
<html>
<head>
<script>
function ajax_post(){
document.getElementById("status").innerHTML = "processing...";
$.post("server.php", { username: $("#userName").val() }, function(data) {
$("#status").html(data);
})
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Username: <input id="userName" name="userName" type="text"> <br><br>
<input name="myBtn" type="submit" value="Check" onclick="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>
我假设我的$ .post语法错误,但我真的不明白。
答案 0 :(得分:3)
试试这个我执行了这段代码,它对我有用。
的index.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function ajax_post(){
document.getElementById("status").innerHTML = "processing...";
console.log($("#userName").val());
$.post("server.php", { username: $("#userName").val() }, function(data) {
$("#status").html(data);
})
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Username: <input id="userName" name="userName" type="text"> <br><br>
<input name="myBtn" type="submit" value="Check" onclick="ajax_post()"> <br><br>
<div id="status"></div>
</body>
</html>
Server.php
<?php
if(!empty($_POST['username'])){
$data = $_POST['username'];
echo 'You are now registered,' . $data;
$fname = "save.text";
$file = fopen($fname, 'a');
fwrite($file, $data . "\n");
fclose($file);
}
?>