我有一个HTML表单(见下面的代码)与ajax按钮。我想通过AJAX post发送表单参数。如何通过JavaScript Ajax POST发送HTML表单的表单参数?
我的问题是,我不知道如何定位HTML表单字段的值(用户插入的值)。
如何使用JavaScript通过ajax post发送HTML参数?
仅供参考:我不想使用formData。
下面是代码:
<body>
<form id="my-form-id" method="post" action="Calendar_form3.php">
Year:<INPUT NAME="gregorian_year" SIZE=4 MAXLENGTH=4 value="2016">(1-6000)
Latitude: <INPUT NAME="latitude" value="40.7127">
Longitude: <INPUT NAME="longitude" value="-74.0059">
<button id="ajax-button" type="button">Ajax button</button>
</form>
<script>
function displayCalendar() {
var divtarget = document.getElementById("main");
var xhr = new XMLHttpRequest();
xhr.open('post', 'Calendar_form3.php', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
console.log('readyState: ' + xhr.readyState);
if (xhr.readyState == 2) {
divtarget.innerHTML = 'LOADING';
}
if (xhr.readyState == 4 && xhr.status == 200) {
var text = xhr.responseText;
divtarget.innerHTML = text;
}
}
xhr.send(gregorian_year=???&latitude=???&longitude=???);
}
var button = document.getElementById("ajax-button");
button.addEventListener("click", displayCalendar);
</script>
<div id='main'>
result here
</div>
</body>
这里是在Calendar_form3.php
页面的代码:
<?php
echo "ajax working!!";
echo $_POST['gregorian_year'] . $_POST['latitude']. $_POST['longitude'];
?>
我怎样才能完成这个代码行:
xhr.send(gregorian_year=???&latitude=???&longitude=???);
换句话说,给我的HTML表单,我如何通过使用JavaScript的AJAX post发送html参数?