Simple Ajax/Codeigniter request

前端 未结 8 758
無奈伤痛
無奈伤痛 2021-01-25 15:43

I\'m having some issues with ajax and codeigniter. I\'ve already posted another question (link to question) and I thought I solved it, but I did not so I`m asking someone to wri

相关标签:
8条回答
  • 2021-01-25 16:14
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <script type="text/javascript"></script>
    <script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery_v1.9.1.js"> </script>
    <script type="text/javascript" src="<?php echo base_url();?>assets/js/script.js">            </script>
    <style type="text/css">
      #number {
        display: block;
        text-align: center;
        width: 100px;
        height: 30px;
        margin: auto auto;
        line-height: 30px;
        border: 1px solid #999999;
        border-radius: 5px;
      }
    
    </style>
    </head>
    <script>
    function increase(){
      var number = parseInt($('#number').html()) + 1;
      $.ajax({
          type: 'POST',
          url: '<?php echo base_url()?>welcome/increase',
          data: { increase:number },
          success:function(response){
             $('#number').html(response);
          }
      });
    
    }
    </script>
    <body>
    <span id="number" onclick="increase()">0</span>
    </body>
    </html>
    
    0 讨论(0)
  • 2021-01-25 16:15

    If you are using this ajax in a .php file than you should do something like this to your url:

    function increase(){
    var number = parseInt($('#number').html()) + 1;
    var base_url = "<?php echo base_url();?>";
    $.ajax({
        type: 'POST',
        url: base_url+'welcome/increase',
        data: { increase:number },
        success:function(response){
            $('#number').html(response);
        }
      });
    }
    

    OR if you are doing this in a .js file than you need to add this line inside your head tag

    <script> var base_url = "<?php echo base_url();?>";</script>
    

    And than use this :

    function increase(){
    var number = parseInt($('#number').html()) + 1;
    $.ajax({
        type: 'POST',
        url: base_url+'welcome/increase',
        data: { increase:number },
        success:function(response){
            $('#number').html(response);
        }
      });
    }
    

    Hope that it resolves the problem. However, its always a good idea when developing in the local environment to set the base_url in config.php like this :

    $root = "http://".$_SERVER['HTTP_HOST'];
    $root .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
    $config['base_url']    = $root;
    
    0 讨论(0)
提交回复
热议问题