点击提交beforeSend:
后,但它不会调用success:
,也没有控制台错误。数据也正确提交到数据库!那么为什么它不会调用success:
。请帮忙
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$(".alert").removeClass("hide");
var msg = $.ajax({
type: "GET",
url: actionurl,
async: false
}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function() { // wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
});
});
控制台消息
Object {readyState: 4, responseText: "<strong>Seat Booked Successfully</strong>", status: 200, statusText: "OK"}
答案 0 :(得分:2)
在Ajax电话&#39; dataType&#39; attributes表示客户端(浏览器)可以期望的数据格式。根据错误消息服务器返回&#39;字符串&#39;相反&#39; json&#39;。
但另一方面,给定ajax调用期望后端服务器返回json数据。提供一个 响应中的有效JSON或将数据类型更改为html。
答案 1 :(得分:1)
在您的AJAX通话设置中,您将dataType
设置为json
,但作为回报,您提供了一个字符串。
dataType(默认值:Intelligent Guess(xml,json,script或html)) 您期望从服务器返回的数据类型。如果没有 指定,jQuery将尝试根据MIME类型推断它 响应
所以,你有两个解决方案:
dataType
值(html
)或删除它来要求JSON。答案 2 :(得分:0)
我有类似的问题。当您成功重定向页面时,您需要使用 e.preventDefault(); //阻止页面刷新
在ajax调用之后或
返回false; //阻止页面刷新
这样的事情:
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$( ".alert" ).removeClass( "hide" );
var msg = $.ajax({type: "GET", url: actionurl, async: false}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function(){// wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
return false; e.preventDefault(); //any one of this options to prevent page refresh after ajax call
});
});