Javascript 更好的Ajax设计用另一个div替换div
我不熟悉Ajax。我有一个有“名称”和按钮的模板。单击按钮时,名称和按钮将替换为一些消息。 我的代码工作得很好。 阿贾克斯:Javascript 更好的Ajax设计用另一个div替换div,javascript,jquery,html,css,ajax,Javascript,Jquery,Html,Css,Ajax,我不熟悉Ajax。我有一个有“名称”和按钮的模板。单击按钮时,名称和按钮将替换为一些消息。 我的代码工作得很好。 阿贾克斯: $('fulfillButton').bind('click',function(){ $.ajax({ 键入:“获取”, contentType:“应用程序/json;字符集=utf-8”, url:“/order/${orderID}”, 数据类型:“json”, cache:false, 超时:12000, 成功:功能(数据){ 警惕(“成功”); }, 错误:函数
$('fulfillButton').bind('click',function(){
$.ajax({
键入:“获取”,
contentType:“应用程序/json;字符集=utf-8”,
url:“/order/${orderID}”,
数据类型:“json”,
cache:false,
超时:12000,
成功:功能(数据){
警惕(“成功”);
},
错误:函数(数据、文本状态){
如果(textStatus==“超时”)
{
$(“#主面板”)。替换为(“+”超时,请点击按钮“再次扫描!”+”);
}
其他的
{
var responseText=data.responseText;
var jsonErrorMessage=JSON.parse(responseText);
$(“#主面板”)。替换为(“”+jsonErrorMessage[“body”]+“”);
}
},
});
Html:
<div id="main-panel">
<div class="full-name">
${name}
</div>
<div id
<button id="fulfillButton" type="button" class="action-button shadow animate fulfill-button-color">
FulFill
</button>
</div>
<button id="goBackButton" type="button" class="go-back-button">
Go Back
</button>
${name}
为什么不在html中添加错误消息div(在主面板中,给它们一些ID,比如error1,error2)作为
隐藏你可以有很多解决方案。我给你两个:
第一个解决方案(见javascript)适用于小事情(如错误消息)
第二种方法适用于更大的事情,例如动态创建表单。这称为模板化
//解决方案1
$('fillbutton').bind('click',function(){
$(“#主面板”).replaceWith($('').addClass('error-message').html('此处有一些内容。这是通过动态创建div、添加错误消息类和添加内容来添加的”);
});
//解决方案2
$('fillbutton2').bind('click',function(){
$(“#主面板”).replaceWith($(“#错误消息模板”).clone().removeClass('hidden').html('此处的某些内容2。这是通过克隆现有隐藏div、删除隐藏类并替换内容来添加的。');
});
。错误消息{
边框:1px实心#f00;
}
#主面板{
边框:1px实心#中交;
}
.隐藏
{
显示:无
}
${name}
完成
完成2
回去
我更新了答案,根据我的建议更改了给定的函数。我是否可以删除整个“#主面板”并为错误消息创建一个新的div(隐藏)?当然,您可以将#主面板
之外的错误div添加为隐藏。然后,当发生错误时,调用$(“#主面板”)。remove()$(“#error1”).show();
这是您想要的吗?
<div id="main-panel">
<div class="full-name">
${name}
</div>
<div id
<button id="fulfillButton" type="button" class="action-button shadow animate fulfill-button-color">
FulFill
</button>
</div>
<button id="goBackButton" type="button" class="go-back-button">
Go Back
</button>
$('#main-panel').replaceWith('<div class="error-message">' + jsonErrorMessage["body"] + '</div>');
error: function (data,textStatus) {
$('#main-panel').find('*').not('.error-message').remove();//Remove everything except from the error-message divs
if(textStatus == "timeout")
{
$('#error1').html('Timeout, please clcik the button beblow to scan again!');
$('#error1').show();
}
else
{
var responseText = data.responseText;
var jsonErrorMessage = JSON.parse(responseText);
$('#error2').html(jsonErrorMessage["body"]);
$('#error2').show();
}
},