我发送ajax调用到控制器方法然后该方法检查数据是否存在然后echo true 如果在数据库中找不到数据然后echo false
问题是我无法在ajax成功函数中得到控制器方法的真假
控制器
interface Example {
static void doJob1(String arg) {
verifyArg(arg);
...
}
static void doJob2(String arg) {
verifyArg(arg);
...
}
private static void verifyArg(String arg) {
...
}
}
调用Ajax
public function ajax_load()
{
$project_id =$this->input->post('account');
$this->db->select('Project_id');
$this->db->from('proposal');
$this->db->where('Project_id',$project_id);
$query = $this->db->get()->row();
if($query){
echo "true";
}else{
echo "false";
}
}
答案 0 :(得分:0)
您必须从控制器返回true或false值,如
if($query){
$arr=["true"];
echo json_encode($arr);
}else{
$arr=["false"];
echo json_encode($arr);
}
Ajax调用
$.ajax({
url: "<?php echo base_url();?>proposal/ajax_load",
type: 'POST',
dataType: 'json',
data : {"account" : project_id},
success: function(result){
if(result[0]==="true"){
$("#err").show();
$("#err").html("Project id already exist");
$(".btn").prop('disabled', true);
}else if(result[0]==="false"){
$("#err").hide();
$(".btn").prop('disabled', false);
}
}
});
答案 1 :(得分:0)
此代码适用于您,除了您正在撰写的查询类型之外。下次尝试显示完整代码以获得更快的帮助。 Stacoverflow充满了工程师,没有人窃取您的代码所以我想知道为什么要将它发送到中途。
好的确保你的后端工作正常
<html>
<head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//$('#result').click(function(){
var project_id = '1';
$('#loader').fadeIn(400).html('Please Wait. Data is being Loaded');
// assuming that you want query result by posting a variable
var datasend = "account="+ project_id;
$.ajax({
type:'POST',
url:'data.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
//display image loader or text to alert the use that content is being loaded
$('#loader').hide();
if(msg=='true'){
alert('true');
// and display result
$('#result').fadeIn('slow').prepend(msg);
}else{
alert('false');
}
}
});
//})
});
</script>
<div id="loader"></div>
<div id="result"></div>
</body></html>
<强> data.php 强>
public function ajax_load()
{
$project_id =$this->input->post('account');
$this->db->select('Project_id');
$this->db->from('proposal');
$this->db->where('Project_id',$project_id);
$query = $this->db->get()->row();
if($query){
echo "true";
}else{
echo "false";
}
}