[英]How to send ajax to the same page?
我正在使用純js向其他.php頁面發送ajax請求,我對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>
這是可能的。 在服務器上,您只需要驗證ajax請求(當您使用ajax發出請求時,標頭X-Requested-With: XMLHttpRequest
將附加到請求)。 如果你想讓它更容易,你可以添加新的參數到url,注意服務器知道這是一個ajax請求,如: ajax-thing.php?uname='+uname+'&age='+age + '&ajax=1'
,如果是ajax請求,則返回您想要的任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.