在回答具体问题之前,我需要解释几个基本步骤。
首先,有问题的应用程序处理客户在线预约的管理。
顾客在填写了美容中心的护理表格并提供了他们的信息后,就会进入确认页面。
现在这个页面执行ajax请求,将约会存储在数据库中。
如果一切都成功,则会显示一个包含约会详细信息的页面,并显示成功消息。
问题是该页面当前仅显示在响应中,即选项卡网络控制台浏览器中。
所以我的问题很简单:How can I replace the entire structure of the html page with actual one shown in the response?
我在网上甚至在StackOverflow上发现了很多问题。但所有这些都局限于对div的追加。我不需要挂起,还需要替换<html>
,如何重写html页面。我不知道该怎么做,我需要你的建议。
为了完整起见,这是返回给我的ajax响应html:的代码
$.ajax({
'type': 'POST',
'url': 'backend_api/ajax_save_appointment',
'data': postData,
'success': function(response)
{
console.log(response);
},
'error': function(jqXHR, textStatus, errorThrown)
{
console.log('Error on saving appointment:', jqXHR, textStatus, errorThrown);
}
});
如果您的响应包括<head>
和<body>
标签:
$("html").html(response);
。
如果不是,而且这只是内容,那么就做:
$("body").html(response);
。
如果响应是html内容,则可以使用以下代码行:
...
'success': function(response)
{
$("body").html(response);
}
...
更新:
这将很难取代html标签,但你可以做的是:
...
'success': function(response)
{
$("html").html($("html", response).html());
}
...
使用jquery解析响应,获取html的内容并替换当前html 的内容
这个问题已经在这里处理过了:用通过AJAX 检索的内容替换HTML页面
基本上,你可以试试(我的坏消息是,这不适用于IE):
document.open();
document.write(newContent);
document.close();
或者,由于您使用的是jquery
$("body").html(data);
问候
也许您可以在"success"-函数中使用以下代码重定向到不同的路由。window.locationhref='http://host.local/path/to/appointment-details';
@JudgeProhet在我看来,您不需要AJAX请求。这样做没有好处。如果更新了整个页面,则可以通过普通的HTTP请求来完成。若您想使用AJAX,您可以简单地使用JavaScript重定向到包含约会详细信息的新页面。
$.ajax({
'type': 'POST',
'url': '/backend/ajax_save_appointment',
'data': postData,
'success': function(response)
{
console.log(response);
// redirect browser to new location
window.location.href = '/backend/appointment_details';
},
'error': function(xhr, status, error)
{
console.log('Error on saving appointment:', xhr, status, error);
// display error message to the user
}
});
我没有足够的代表留下评论(!!),但@fribu智能解决方案的UPDATE回答(https://stackoverflow.com/a/33914275/1428972)应标记为正确的,使用:
$("html").html($("html", response).html());
这通过ajax完全替换了页面。这可以正常工作,而其他人即使使用"html"
也不能完全工作。
我知道这是一篇旧帖子,但它刚刚解决了我在同一问题上的问题!:)