简体   繁体   English

Codeigniter中的Ajax请求

[英]Ajax request in Codeigniter

I have been trying to create an ajax request in codeigniter. 我一直在尝试在codeigniter中创建一个ajax请求。 I've seen this question: Simple Ajax/Codeigniter request but I wasn't able to absorb that as there were the answers in which people were using PHP inside Javascript . 我已经看到了这个问题: 简单的Ajax / Codeigniter请求,但是由于人们在Javascript中使用PHP的答案,我无法理解这一点。 I didn't know it was possible, however I gave that a try but it seems like the PHP wasn't being executed. 我不知道这是有可能的,但是我尝试了一下,但似乎未执行PHP。

So here are my questions: 所以这是我的问题:

  1. Is it really possible to use PHP inside Javascript, or am I mistaken? 真的可以在Javascript中使用PHP,还是我弄错了?
  2. What's the right way to perform an Ajax request in Codeigniter ? 在Codeigniter中执行Ajax请求正确方法是什么? What I've tried is the following: 我尝试了以下内容:

var param = {name : event_name, date : event_date, time : event_time};

            $.ajax({
                // As seen from the question here at stackoverflow.
                url : "<?php echo base_url('event/new_event'); ?>",
                type : 'POST',
                data : param,
                beforeSend : function(){ },
                success : function(){
                    alert("Event created! Feel free to add as much details as you want.");
                    namebox.val("");
                    $("#new-event-modal").find(".close").trigger('click');
                    window.location.href = "<php echo base_url('user/dashboard'); ?>";
                },
                complete : function(){ },
                error : function(){ }
            });

I know the possibility that I could hardcode the URL in the request but that wouldn't be a good practice!! 我知道有可能在请求中对URL进行硬编码,但这不是一个好习惯!

the easiest way for you to accomplish this is by using some jquery: 实现此目的最简单的方法是使用一些jquery:

function getBaseUrl() {
    var l = window.location;
    var base_url = l.protocol + "//" + l.host + "/" + l.pathname.split('/')[1];
    return base_url;
}

var postdata = {name : event_name, date : event_date, time : event_time};
var url = getBaseUrl()+"/event/new_event";

$.post(url, postdata, function(result){
  ...alert(result);
});

or call it straight from JS by caching it: 或通过缓存直接从JS调用它:

<script> 

    var test = "<?php echo base_url(); ?>"+"event/new_event";
    alert(test);

</script>

Here is a dirty hack that I was going to use: 这是我要使用的一个肮脏的技巧

  1. Create a hidden field somewhere on the page and when this page loads echo out the base_url() as the value of that hidden field . 在页面上的某处创建一个隐藏字段 ,并在此页面加载时回显base_url()作为该隐藏字段的值
  2. Now when you want to make an ajax request, access that hidden field and grab the base url and use it however you want. 现在,当您要发出ajax请求时, 访问该隐藏字段并获取base url并根据需要使用它。

The right way is always the simplest way, there is no need to import Jquery in your client if you are not already using it. 正确的方法始终是最简单的方法,如果尚未使用Jquery,则无需在客户端中导入它。

This is your controller 这是你的控制器

<?php if (!defined('BASEPATH')) die();
class Example_ctrl extends CI_Controller {

    public function ajax_echo()
    {
        // get the ajax input
        $input = json_decode(file_get_contents('php://input'));

        // $input can be accessed like an object
        $password = $input->password;
        $name = $input->name;

        // you can encode data back to JSON
        $output = json_encode($input);

        // and the response goes back!
        echo($output);
    }
}
?>

This goes into your client 这进入您的客户

<script>
    // here's the data you will send
    var my_data = {name: "Smith", password: "abc123"};

    // create the request object
    var xhr = new XMLHttpRequest();

    // open the object to the required url
    xhr.open("POST", "example_ctrl/ajax_echo", true);

    // on success, alert the response
    xhr.onreadystatechange = function () {
        if (xhr.readyState != 4 || xhr.status != 200)
            return;
        alert("Success: " + xhr.responseText);
        };

    // encode in JSON and send the string 
    xhr.send(JSON.stringify(my_data));
</script>

There is no better way to do this . 没有更好的方法可以做到这一点。

Php codes can't be executed from external javascript files. 不能从外部javascript文件执行php代码。

Try any of these :- 尝试以下任何一种方法:-

1) base_url() is something's that's will not change , better store it in cookie and then access it in both server side code and client side code 1)base_url()不会改变,最好将其存储在cookie中,然后以服务器端代码和客户端代码访问

2) you can store the same base_url() in local storage , it will be available in your external JavaScript files 2)您可以在本地存储中存储相同的base_url(),它将在您的外部JavaScript文件中可用

Hope it helps you :) 希望它能对您有所帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM