<input type="text" user" id="nick" />
<input type="text" user" id="message" />
<a href="#">Send</a>
让我们保持简单。我有两个输入框和一个发送链接。我想将昵称和消息发送到 shoutbox.php,在那里我将在数据库中插入这些值,并希望从数据库中获取所有结果并将其显示在前端。
现在我已经实现了保存在数据库部分,但我无法将值从数据库取回前端。
我迫切需要一个jquery函数,我可以在其中发送参数,它将为我完成所有工作。我希望你们能为自己提供这样的功能。
使用 jQuery Ajax 方法将数据发送到shoutbox.php
:
$.ajax({
type: "POST",
url: "shoutbox.php",
data: { nick: "val_of_nick", msg: "val_of_msg" },
success: function(data) {
alert('Loaded: ' + data);
}
});
现在在您的shoutbox.php
:
//read the sended data
$nickname = $_POST['nick'];
$msg = $_POST['msg'];
//to send data back, just use echo/print
echo 'You sended nickname: ' . $nickname . ' and msg: "' . $msg . '"';
如果运行此代码,则 js 警报将显示 shoutbox.php
中的echo
行。
希望这有帮助!
有关 jQuery ajax 的更多信息: 信息
举个例子:
.HTML
<form id="myform">
<input type="text" user" id="nick" name="nickname" /> <!-- use name ->
<input type="text" user" id="message" name="message"/> <!-- use name -->
<a href="#" id="send">Send</a>
</form>
jQuery
$('#send').on('click', function(e) {
e.preventDefault(); // prevent page reload on clicking of anchor tag
$.ajax({
type: 'POST',
url: 'url_to_script',
data: $('#myform').serialize(),
dataType: 'json', // if you want to return JSON from php
success: function(response) {
// you can catch the data send from server within response
}
});
});
现在在你的PHP端,你可以通过ajax捕获发送值,如下所示:
<?php
...
$nickname = $_POST['nickname'];
$message = $_POST['message'];
......
?>
相关参考文献:
.serialize((
.ajax((