使用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:
方法 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);
}
});
方法二
$("#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');
});
.success()
、.error()
和.complete()
回调自jQuery 1.8起已被弃用。为了准备将来删除它们,应改用.done()
、.fail()
和.always()
。
MDN:abort()
。如果请求已经发送,则此方法将取消请求。
因此,我们已成功发送Ajax请求,现在是时候从服务器获取数据了。
PHP
由于我们在Ajax调用中进行了POST请求(type: "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);
});
有几个简写方法可供使用。您可以使用下面的代码,它完成相同的工作。
var ajaxRequest= $.post("test.php", values, function(data) {
alert(data);
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});