要使用 jQuery 发出 Ajax 请求,您可以通过以下代码来完成。
HTML:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>
JavaScript:
方法一
/* Get from elements values */
var values = $(this).serialize();
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// You will get response from your PHP page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
方法二
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
var ajaxRequest;
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get from elements values */
var values = $(this).serialize();
/* Send the data using post and put the results in a div. */
/* I am not aborting the previous request, because it's an
asynchronous request, meaning once it's sent it's out
there. But in case you want to abort it you can do it
by abort(). jQuery Ajax methods return an XMLHttpRequest
object, so you can just use abort(). */
ajaxRequest= $.ajax({
url: "test.php",
type: "post",
data: values
});
/* Request can be aborted by ajaxRequest.abort() */
ajaxRequest.done(function (response, textStatus, jqXHR){
// Show successfully for submit message
$("#result").html('Submitted successfully');
});
/* On failure of request this function will be called */
ajaxRequest.fail(function (){
// Show error
$("#result").html('There is error while submit');
});
自 jQuery 1.8 起,.success()、.error() 和 .complete() 回调已被弃用。要为最终删除准备您的代码,请改用 .done()、.fail() 和 .always()。
MDN: abort() 。如果请求已经发送,此方法将中止请求。
所以我们已经成功发送了一个 Ajax 请求,现在是时候将数据抓取到服务器了。
PHP
当我们在 Ajax 调用 (type: "post") 中发出 POST 请求时,我们现在可以使用 $_REQUEST 或 $_POST 获取数据:
$bar = $_POST['bar']
您也可以通过简单的方式查看 POST 请求中的内容。顺便说一句,确保设置了$_POST。否则会报错。
var_dump($_POST);
// Or
print_r($_POST);
您正在向数据库中插入一个值。在进行查询之前,请确保您敏感或转义所有请求(无论您是进行 GET 还是 POST)都正确。最好的办法是使用准备好的语句。
如果您想将任何数据返回到页面,只需像下面这样回显该数据即可。
// 1. Without JSON
echo "Hello, this is one"
// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));
然后你可以得到它:
ajaxRequest.done(function (response){
alert(response);
});
有几个shorthand methods。您可以使用以下代码。它做同样的工作。
var ajaxRequest= $.post("test.php", values, function(data) {
alert(data);
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});