我对jQuery/ajax
有点不熟悉。
我一直在使用$.post..
来发送和接收消息,但它极大地改进了我的网站。
我需要一个将ajax cal发送到服务器进行验证的工具
如果验证成功,则我希望服务器重定向如果没有,它应该返回到页面并显示错误消息。
我的问题是哪个jQuery
调用最适合此操作。
根据我的经验,当我在服务器上使用$.post('....')
和重定向时,由于某种原因,它不会重定向。
您可以在ajax调用中使用另一个ajax调用,或者只触发表单提交。
$("form").on("submit", function (e) {
var $this = $(this);
e.preventDefault();
$.get("validate.php", $this.serialize()).done(function (valid) {
if (valid) {
$this.trigger("submit");
//OR
$.post("submit.php").done(function () { window.location = next; });
}
});
});
如果您使用header()使用PHP重定向,它将不会使用ajax重定向,因为内容已经发送到客户端(您只能在打磨任何数据之前使用此功能)
您应该尝试使用window.location通过javascript重定向。href="my new page"
你可以在以下链接找到更多信息
http://ntt.cc/2008/01/21/5-ways-to-redirect-url-with-javascript.htmlhttp://php.net/manual/en/function.header.php
如果您没有使用PHP重定向,那么我向道歉
您可以使用$.post
的底层函数,即$.ajax
$.ajax({
url: 'url',
data: 'json_or_string',
type: 'POST',
dataType: 'json',
success: function(json) {
if (json.clear == 1) {
document.location.href = "redirect";
} else {
$('#errormessage').html('Error Validation');
}
},
error: function (error) {
},
});
JS:
$('#submitButtton').click(function(){
$.ajax({
dataType: "json",
type: 'POST',
url: url/to/ajax-results.php',
data: { $('form#my-form').serialize(); }
}).done(function(data){
if(data.response == 'error') {
$('#results').html('<div class="error">'+data.report+'</div>');
$('#results').show();
return false;
}
window.location.href = data.redirect
});
});
PHP:
<?php
$errors = array();
$val1 = $_POST['val1'];
if(empty($val1)) {
$errors[] = 'val1 cannot be empty';
}
if(count($errors) > 0) {
echo json_encode(array(
'response' => 'error',
'report' => 'send your errors array, or custom error message'
));
exit();
} else {
echo json_encode(array(
'response' => 'ok',
'redirect' => 'http://www.domain.com/url/to/redirect'
));
exit();
}
?>