要使用jQuery发出Ajax请求,您可以通过以下代码执行此操作。
网页:
<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:
方法 1
var values = $(this).serialize();
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
方法 2
$("#foo").submit(function(event) {
var ajaxRequest;
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
ajaxRequest= $.ajax({
url: "test.php",
type: "post",
data: values
});
ajaxRequest.done(function (response, textStatus, jqXHR){
$("#result").html('Submitted successfully');
});
ajaxRequest.fail(function (){
$("#result").html('There is error while submit');
});
、 和回调在 jQuery 1.8 中已弃用。若要为最终删除它们准备代码,请改用 、 和 。.success()
.error()
.complete()
.done()
.fail()
.always()
MDN: abort()
.如果已发送请求,则此方法将中止请求。
因此,我们已经成功发送了Ajax请求,现在是时候将数据抓取到服务器了。
菲律宾比索
当我们在 Ajax 调用 () 中发出 POST 请求时,我们现在可以使用 以下任一方式获取数据:type: "post"
$_REQUEST
$_POST
$bar = $_POST['bar']
您还可以通过任何一种方式查看您在POST请求中获得的内容。顺便说一句,请确保已设置。否则,您将收到错误。$_POST
var_dump($_POST);
print_r($_POST);
并且您正在将值插入到数据库中。在进行查询之前,请确保正确敏感化或转义所有请求(无论是发出 GET 还是 POST)。最好的办法是使用预准备的语句。
如果您想将任何数据返回到页面,只需像下面这样回显该数据即可。
echo "Hello, this is one"
echo json_encode(array('returned_val' => 'yoho'));
然后你可以得到它,就像这样:
ajaxRequest.done(function (response){
alert(response);
});
有几种速记方法。您可以使用以下代码。它执行相同的工作。
var ajaxRequest= $.post("test.php", values, function(data) {
alert(data);
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});