我想在我的视图中设置条件但我不知道如何操作。如果来自控制器的请求实现了他,则成功div出现,否则失败div。当时我只是在警告框中打印true和false。 这是我的观点:
<div class = "success">operation done successfully </div>
<div class = "failiour">operation done successfully </div>
//these are the two divs on which i want to apply a condition
<form>
</form>
<script type="text/javascript">
$('#btn').click(function() { // $("#form").serialize()
var item_name = $('#item_name').val();
var cat_id = $('#selsear').val();
if (!item_name || item_name == 'Name') {
alert('Please enter Category Name');
return false;
}
var form_data = {
item_name: $('#item_name').val(),
cat_id: $('#selsear').val(),
};
$.ajax({
url: "<?php echo site_url('itemsController/additems'); ?>",
type: 'POST',
data: form_data,
dataType: 'json',
success: function(msg) {
if(msg.res == 1)
{
alert(true);
}
else{
alert(false);
}
}
});
return false;
});
</script>
我的控制器
function additems(){
//getting parameters from view
$data = array(
'item_name' => $this->input->post('item_name'),
'cat_id' => $this->input->post('cat_id')
);
//$is_ajax = $this->input->post('ajax'); //or use this line
//$this->input->is_ajax_request();
$result = array();
$this->load->model('itemsModel');
$query = $this->itemsModel->addItemstoDB($data);
if ($query){ //&& any other condition
$result['res'] = 1;//process successful - replace 1 with any message
}
else
{
$result['res'] = 0;//process failed - replace 0 with any message
}
echo json_encode($result);//at the end of the function.
}
}
答案 0 :(得分:0)
在成功和失败div中设置display none to css,然后执行以下操作:
$.ajax({ url: "", type: 'POST', data: form_data, dataType: 'json', success: function(msg) { if(msg.res == 1) { $(".success").fadeIn(500).delay(2000).fadeOut(500); } else { $(".failiour").fadeIn(500).delay(2000).fadeOut(500); } } });
答案 1 :(得分:0)
首先隐藏你的div
<div class = "success" style="display:none;">operation done successfully </div>
<div class = "failiour" style="display:none;">operation done successfully </div>
然后如果您多次获得请求
$.ajax({
url: "",
type: 'POST',
data: form_data,
dataType: 'json',
success: function(msg) {
if(msg.res == 1)
{
$(".success").show();
$(".failiour").hide();
}
else
{
$(".failiour").show();
$(".success").hide();
}
}
});
答案 2 :(得分:0)
在你的剧本中,
//supposing you are getting the result in response varible
if(response == true) // simply write: if(response)
{
document.getElementById('success').style.display='block';
document.getElementById('failure').style.display='none';
}
else
{
document.getElementById('success').style.display='none';
document.getElementById('failure').style.display='block';
}
//根据您的要求为div添加ID并添加样式块/无
<div id="success" style="display:block;"></div>
<div id="failure" style="display:none;"></div>