有多种方法可以创建AJAX调用。最简单的就是使用Javascript框架,如Mootools或JQuery。 Ajax很简单,这种方式。检查http://demos111.mootools.net/Ajax.Form Mootools演示和jQuery在这里http://docs.jquery.com/Tutorials。
逻辑非常简单。将值添加到文本框中,以便在值更改时保存该框。您的事件函数将生成Ajax请求并将其发送到服务器,如果您选择,您可以使用此响应来让用户知道保存事件的状态。
这里是我为你写的快速的东西,可能有助于理解。将需要包括Mootools库。可能有错误,但Ajax调用的概念在那里。 page = index.php
<?php
// PHP before anything else...
//
// Check to see if task is specified and need to save changes
if (isset($_POST['task']) && $_POST['task'] == 'save') {
// mysql connection
$text = $_POST['name'];
// insert query
$isSuccess = 'Status of SAVING CHANGES';
// Output... output will be used by 'update' to set value of <div id="log">...</div>
// so user knows what is happening
echo $isSuccess ? 'Successfully Saved' : 'Failed to Save';
exit();
}
?>
<html>
<head>
<!-- NEED TO INCLUDE MOOTOOLS LIBRARY -->
<script type="text/javascript">
window.addEvent('domready', function(){
$('name').addEvent('blur', saveChanges);
/**
* Generates request and saves changes
*/
function saveChanges(){
// URL which will be called
var url = "index.php";
// New Ajex request. Note that it will be sent because of .request() at the end
new Ajax(url, {
// Method : post/get
method: 'post',
// Data to be passed
data :{
name : $('name').value,
task : 'save'
},
// Output of the AJAX will be set to this element
update: $('log')
}).request();
}
});
</script>
</head>
<body>
<form action="index.php" onsubmit="return false">
<div id="log"></div>
<!-- SOME CONTENT ... -->
<input type="text" name="name" id="name" value="">
</form>
</body>
</html>