javascript 简单的 Ajax/Codeigniter 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16378887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:24:30  来源:igfitidea点击:

Simple Ajax/Codeigniter request

javascriptajaxcodeigniteronclick

提问by mihajlo

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 write simple code with ajax/codeigniter that will increase number inside div/span on click.

我在使用 ajax 和 codeigniter 时遇到了一些问题。我已经发布了另一个问题(问题链接),我以为我解决了它,但我没有解决,所以我要求某人使用 ajax/codeigniter 编写简单的代码,这将在单击时增加 div/span 内的数字。

I`m trying last few days to do this, but constantly getting errors..My CI setting are :
base_url : localhost/test/
index:index.php
autoload:url
default controller:welcome (I left it so just for this test)

我真的想最近几天要做到这一点,但经常收到errors..My CI设定为:
BASE_URL:localhost/test/
指数:index.php文件
自动加载:URL
默认控制器:欢迎(我把它这样只是为了本次测试)

I would be more than happy to have simple example to do this. I tried also, again, but without any luck. Here's what I tried this time :

我会很高兴有简单的例子来做到这一点。我也试过,再次,但没有任何运气。这是我这次尝试的:

Controller (welcome.php)

控制器(welcome.php)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {


function __construct()
    {
        parent::__construct();
    }

public function index()
{
    $this->load->view('welcome_message');
}

function increase(){
    $increase = $this->input->post('increase');
    echo increase++;
}
}

JS (Ajax)

JS(阿贾克斯)

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

}

View (HTML/CSS)

视图 (HTML/CSS)

<!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>
<body>
    <span id="number" onclick="increase()">0</span>
</body>
</html>

I'm using latest xampp on windows 7. Error that I get when I click on span - POST http://localhost/test/localhost/test/welcome/increase 404 (Not Found)

我在 Windows 7 上使用最新的 xampp。单击 span 时出现错误 - POST http://localhost/test/localhost/test/welcome/increase 404 (Not Found)

回答by Philip

You must submit the CSRF token from cookies otherwise the request will be invalid, if you have CSRF enabled in config.php.

您必须从 cookie 提交 CSRF 令牌,否则请求将无效,如果您在 config.php 中启用了 CSRF。

You can use this pluginto retrieve cookies in javascript. And simply pass it to CI.

您可以使用此插件在 javascript 中检索 cookie。并简单地将其传递给 CI。

ci_token

ci_token

and

ci_cookie

ci_cookie

keys may be different and can be found in config.php

键可能不同,可以在 config.php 中找到

I would also suggest setting up a route for the request and using

我还建议为请求设置路由并使用

site_url()

site_url()

over

超过

base_url()

base_url()

var SITE = "<?php echo site_url();?>" // GLOBAL variable so your javascripts can be external

-

——

var data = { 'ci_token' : $.cookies.get('ci_cookie'), 'increase' : parseInt(number)}
$.ajax({
    url : SITE + "/link/to/controller/method",
    data : data,
});

回答by Azam Alvi

First You should define your site base_url in application/config file then use this base_url with your ajax page call from where your call goes. Suppose your base_urlis http://localhost/test/

首先,您应该在应用程序/配置文件中定义您的站点 base_url,然后将此 base_url 与您的 ajax 页面调用一起使用。假设你base_urlhttp://localhost/test/

function increase(){
   var number = parseInt($('#number').html()) + 1;
   $.post('<?php echo base_url()?>welcome/increase',{number :number},function(response){
          $('#number').html(response);
   });    
}

then change your increase function in controller like this

然后像这样改变控制器中的增加功能

function increase(){
   $increase = $_POST['number'];
echo increase++;

}

}

回答by Raghvendra Mishra

try this :

试试这个 :

function increase(){
        var number = parseInt($('#number').html()) + 1;
        $.ajax({
            type: 'POST',
            url: 'localhost/test/Welcome/increase/',
            data: "increase=" + number,
            dataType: "text",
            success:function(response){
                $('#number').html(response);
            }
        });

 }

回答by Iftikhar1487

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

如果你在 .php 文件中使用这个 ajax,那么你应该对你的 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

或者,如果您在 .js 文件中执行此操作,则需要在 head 标记中添加此行

<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 :

希望它能解决问题。但是,在本地环境中开发时,在 config.php 中设置 base_url 总是一个好主意,如下所示:

$root = "http://".$_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
$config['base_url']    = $root;

回答by bipen

use site_url()of codeigniter

使用代码site_url()点火器

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

}

}

however, adding http://in front of localhost should work

但是,http://在 localhost 前面添加应该可以工作

 url: 'http://localhost/test/welcome/increase',

but it is always better and recommended to use site_url()if you are calling a controller in CI...so that this won't give you errors while when you upload it to live server.

site_url()如果您在 CI 中调用控制器,它总是更好并建议使用......这样当您将其上传到实时服务器时,这不会给您错误。

回答by Alverated

In your ajax, don't use external link for your JS just use internal.

在您的 ajax 中,不要为您的 JS 使用外部链接,只需使用内部链接。

Make sure that you set your $config['base_url'] = http://localhost/test/in config.php

确保http://localhost/test/在 config.php 中设置了 $config['base_url'] =

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);
        }
   });

}

回答by Alverated

<!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>

回答by Mehdi

View::::::    
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="<?php echo base_url();?>css/jquery.js"> </script>
<style type="text/css">
#number {
display: block;
text-align: center;
width: 100px;
height: 30px;
margin: 50px auto;
line-height: 30px;
border: 1px solid #999;
border-radius: 5px;
}
body{
cursor: default;
}
</style>
</head>
<script>
function increase(){
var number = parseInt($('#number').html());
$.ajax({
  type: 'POST',
  url: '<?php echo base_url()?>main/samp_data',
  data: { increase:number },
  success:function(response){
     $('#number').html(response);
  }
  });
 }
</script>
<body>
<span id="number" onclick="increase()">0</span>
</body>
</html>




Controller::::::
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller {

    public function index(){
        $this -> load -> view('sample_view');
    }

    public function samp_data(){
        $increase = $this->input->post('increase');
        echo ++$increase;
    }
}