我正在使用纯js将ajax请求发送到其他.php页面,我对ajax概念非常陌生,所以我了解不多。 我见过 jQuery ajax,但我更喜欢学习纯 js ajax,这样我可以了解 ajax 的工作原理。
我需要将ajax发送到同一页面,而不是发送到另一个页面来处理数据。可以这样做吗?以及如何?
我的索引页:
<div id="response"></div>
<form method="post" id="myForm">
<span>Username: </span>
<input type="text" name="uname" id="uname">
<span>Age: </span>
<input type="number" name="age" id="age">
<input type="submit" name="submit" value="Submit"><br>
</form>
<script src="js/app.js"></script>
我的PHP代码:
<?php
if(isset($_GET['uname']) && isset($_GET['age'])) {
$name = trim(strip_tags($_GET['uname'])); $age = trim(strip_tags($_GET['age']));
echo !empty($name) && !empty($age) ?
'<p style="color:green">Hello: '.$name.' You\'re '.$age.' Years Old :D</p>' :
'<p style="color:red">Please Write your Name and Your Age</p>';
}
我的ajax代码:
window.onload = function() {
var myForm = document.getElementById('myForm');
myForm.onsubmit = function() {
// Create the object from XMLHttpRequest
var xhttp = (window.XMLHttpRequest) ? new window.XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"),
uname = document.getElementById('uname').value,
age = document.getElementById('age').value,
result = document.getElementById('response'),
url = 'ajax-thing.php?uname='+uname+'&age='+age;
xhttp.onload = function() {
result.innerHTML = xhttp.responseText;
};
xhttp.open('GET', url, true);
xhttp.send();
return false;
}
};
最佳答案
尝试使用 Jquery
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'ajax-thing.php',
data: "uname="+uname+"&age="+age,
success: function(data) {
console.log(data); // it will show the result in console
}
});
});
</script>
关于javascript - 如何发送ajax到同一页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42382584/