拼命地需要一个ajax函数用于jquery

时间:2012-07-29 09:01:53

标签: php jquery ajax

<input type="text" user" id="nick" />
<input type="text" user" id="message" />
<a href="#">Send</a>

让我们保持简单。我有两个输入框和一个发送链接。我想将昵称和消息发送到shoutbox.php,我将在数据库中插入这些值,并希望从数据库中获取所有结果并在前端显示。

现在我已经实现了数据库部分的保存,但我无法从数据库中恢复到前端的值。

我迫切需要一个jquery函数,我可以在其中发送参数,它将为我完成所有工作。我希望你们可能有这样的功能。

2 个答案:

答案 0 :(得分:1)

使用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提醒会显示echo的{​​{1}}行。

希望这有帮助!

有关jQuery ajax的更多信息:info

答案 1 :(得分:0)

只是一个例子:

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'];
  ......
?>

相关参考: