0

我需要codeigniter ajax响应,请帮我做..请询问任何其他进一步的要求..

我在添加这种 Ajax 时得到空响应谢谢

function Ajax_newsletter()
{

    var str=document.getElementById("sub_email").value;

    if (str.length==0)
      { 
         document.getElementById("txtHint").innerHTML="";

      }
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            alert(xmlhttp.responseText);
            if(xmlhttp.responseText==1)
            {
            document.getElementById("txtHint").innerHTML='User Already Exist..';
            }
            elseif(xmlhttp.responseText==0)
            {
                document.getElementById("txtHint").innerHTML='Newsletter subscribed..';
            }
        }
      }
    xmlhttp.open("GET","<?php echo base_url();?>index.php/ajax/checkuser/"+str,true);
    xmlhttp.send();     


}
4

2 回答 2

0

我假设您使用的是 PHP、HTML、javascript (jquery)。我会做这样的事情

把它放在你的视图中

$("#form-name").submit(function(e){
    e.preventDefault();
    dataString = $("#form-name").serialize();
    $.ajax({
        type:"POST",
        url:"<?=base_url()?>controller_name/function_name.php",
        data: dataString,
        dataType: 'json',
        success: function(data){
            if(data.response == "success"){
                  alert("YAAAY");
            }else{
                  alert("NOOOO...");  
            }
        }
    });
});

在你的控制器中确保你有这样的东西

public function function_name()
{
    if($this->session->userdata('verified')) 
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('user-name', 'User Name', 'required|xss_clean');

        $this->form_validation->set_error_delimiters('<li>', '</li>');

        if($this->form_validation->run() == FALSE){
            $data['status'] = "failed";
            $data['message'] = "<h4>Failed to add new user, make sure all required information below is correct.<br/>";
            $data['message'] .= "<ul>";
            $data['message'] .= form_error('user-name');
            $data['message'] .= "</ul></h4>";
        }else{   
            // WHAT SHOULD HAPPEN WHEN FORM IS VALID
        }
        echo json_encode($data);
    }else{
            // WHAT SHOULD HAPPEN WHEN UNAUTHENTICATED USER IS ACCESSING THIS FUNCTION
    }
}
于 2013-07-17T08:53:32.553 回答
0

正如您标记的那样,jQuery试试这个:

function ajax_newsletter() {
    var str = $("#sub_email").val();
    if (str.length == 0) {
        $("#txtHint").html("");
    }
    $.get("<?php echo base_url();?>index.php/ajax/checkuser/" + str)
    .done(function(data) {
        console.log(data);
    });
}
于 2013-07-17T08:57:39.580 回答