使用codeigniter_在CodeIgniter中使用Ajax

使用codeigniter

I discovered that it's quite a simple thing and here I show you how to do it. 
我发现这很简单,在这里我向您展示了如何做。

To make the example more interesting, I'll show you how to build a form to allow your user to send you an email, something we all always need. To do it, I'll use CodeIgniter 2.2 (don't worry, the same rules will work with CI 3 if you respect the new rules, overall to capitalize all class file names) and jQuery.

为了使示例更加有趣,我将向您展示如何构建一个表单,以使您的用户向您发送电子邮件,这是我们始终需要的。 为此,我将使用CodeIgniter 2.2(不用担心,如果您遵守新规则,则相同的规则将与CI 3一起使用,总的来说将所有类文件名都大写)和jQuery。


 
The main problem when you want to use Javascript with CI is the CI url structure. As you know, when you have to write a link to a page within a CodeIgniter view, you have to use base_url() method, which returns the root of your site as you have configured it in the config.php.
当您想将Javascript与CI一起使用时,主要问题是CI url结构。 如您所知,当您必须在CodeIgniter视图中编写指向页面的链接时,必须使用base_url()方法,该方法将返回您在config.php中配置网站的根目录。

So, if your site is www.example.com, we can reasonably expect you have in your config.php file the following line:

因此,如果您的网站是www.example.com ,我们可以合理地期望您的config.php文件中包含以下行:

$config['base_url'] = 'http://www.example.com/'; 

This means that in your view, to build a link to the contact page you'll have to write

这意味着在您看来,要建立指向联系页面的链接,您必须编写

<a href="<?php echo base_url('contacts') ?>">Contacts</a> 

But your javascript knows nothing about base_url() and of course you can't use a plain absolute path to link your script in an Ajax call because this just doesn't work: once filtered by CI, the Ajax call is missing like an echo in a desert.

但是您的javascript对base_url()一无所知,并且您当然不能使用普通的绝对路径在Ajax调用中链接您的脚本,因为这是行不通的:一旦被CI过滤,Ajax调用就会像回声一样丢失在沙漠中

So, the first we have to do is to make base_url available for our javascript. Open your footer view (tipically 'footer_view.php') and add following lines:

因此,我们首先要做的是使base_url可用于我们的javascript。 打开页脚视图(通常为“ footer_view.php”),然后添加以下几行:

<script type="text/javascript">
    var baseurl = "<?php print base_url(); ?>";
</script> 

In this case, we'll use a specific javascript file to perform our action and we'll call it sendmail.js (what a fantasy, uh?). So our footer view will look like this one:

在这种情况下,我们将使用特定的javascript文件执行操作,并将其命名为sendmail.js(这是什么幻想,嗯?)。 因此,我们的页脚视图将如下所示:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="<?php echo base_url('assets/js/app.js'); ?>"></script>
<script type="text/javascript">
    var baseurl = "<?php print base_url(); ?>";
</script> 

Now, our sendmail.js knows about base_url() all of what it needs to know, so it'll work like a charm.

现在,我们的sendmail.js知道了base_url()所需要知道的所有内容,因此它就像一个魅力一样工作。

This done, we can proceed, starting by the email form. When the user clicks on the link to open the contact page, the controller method called contacts() load contact_view.php with its header and footer. Take a look at the form:

完成后,我们可以从电子邮件表格开始。 当用户单击链接以打开联系页面时,名为contacts()的控制器方法将使用其页眉和页脚加载contact_view.php。 看一下表格:

<div id="response"></div>
<form>
    <label for="email">Email</label>
    <input id="email" type="text" placeholder="Email" />
    <br>
    <label for="name">Nome</label>
    <input id="name" type="text" placeholder="Name" />
    <br>
    <textarea id="message" placeholder="Your message here..."></textarea>
    <br>
    <button id="send"> Send </button>
</form> 

Well, it doesn't look too nice, but it's just a raw form for our example: making it nice is up to you :-) The only thing I want you notice is the div I placed immediately before the form: it'll hold a success or an error message returned by the method which actually will send our email.

好吧,它看起来并不太好,但是这只是我们示例的原始形式:使它变得更好取决于您:-)我唯一想让您注意的是div紧接在表单之前:它将保留方法发送的成功消息或错误消息,该方法实际上将发送我们的电子邮件。

As you can see, there's no action, no method, no submit: all stuff will be managed by jQuery. Let's go there, now.

如您所见,没有动作,没有方法,没有提交:所有内容都将由jQuery管理。 现在去那儿。

$( document ).on( 'click', '#send', function ( e ) {
    e.preventDefault();
    //hide response if it's visible
    $( '#response' ).hide();
    //we grab all fields values to create our email
    var name = $( '#name' ).val();
    var email = $( '#email' ).val();
    var message = $( '#message' ).val();
    if ( name === '' || email === '' || message === '' )
    {
        //all fields are rquired so if one of them is empty the function returns
        return;
    }
    //if it's all right we proceed
    $.ajax( {
        type: 'post',
        //our baseurl variable in action will call a method in our default controller
        url: baseurl + 'sendmail',
        data: { name: name, email: email, message: message },
        success: function ( result )
        {
            //Ajax call success and we can show the value returned by our controller function
            $( '#response' ).html( result ).fadeIn( 'slow' ).delay( 3000 ).fadeOut( 'slow' );
            $( '#name' ).val( '' );
            $( '#email' ).val( '' );
            $( '#message' ).val( '' );
        },
        error: function ( result )
        {
            //Ajax call failed, so we inform the user something went wrong
            $( '#response' ).html( 'Server unavailable now: please, retry later.' ).fadeIn( 'slow' ).delay( 3000 ).fadeOut( 'slow' );
            $( '#name' ).val( '' );
            $( '#email' ).val( '' );
            $( '#message' ).val( '' );
        }
    } );
} );  

As promised, the code is quite simple. Let me just remind you that the success and error function within the Ajax call are not referred to the sending email action but only to the Ajax call: in other words, the error means the call failed probably because the script couldn't be found and the success means that the script has been reached successfully. So our Ajax call will return success even if the script fails sending our email. You have to keep in mind this when you write the messages that controller method sendmail() will return.

如所承诺的,代码非常简单。 让我提醒您,Ajax调用中的成功和错误功能不涉及发送电子邮件操作,而仅涉及Ajax调用:换句话说,该错误表示该调用失败了,可能是因为找不到该脚本,并且成功表示脚本已成功到达。 因此,即使脚本无法发送我们的电子邮件,我们的Ajax调用也将返回成功。 在编写控制器方法sendmail()返回的消息时,请记住这一点。

And now, let's see the method sendmail():

现在,让我们看一下sendmail()方法:

public function sendmail()
{
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $to = 'yourname@yourdomain.com';
    $subject = 'New message from your site';
    $headers = "From: " . strip_tags($email) . "\r\n";
    $headers .= "Reply-To: ". strip_tags($email) . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    if (mail($to, $subject, $message, $headers))
    {
        echo 'Your message has been correctly sent. Thank you for contacting us: we'll reply as soon as possible<br><h4 style="text-align: right;">Lo Our staff</h4>';
    }
    else
    {
        echo 'Ooops, I'm sorry but something went wrong sending your message. Please contact us at this address: '.safe_mailto( support@yourdomain.com );
    }
} 

As I said before, you have to check if mail() function worked fine and return the appropriate message to your user: the message echoed here is the message that jQuery will make visible in div 'response' as result of the Ajax call.

如前所述,您必须检查mail()函数是否工作正常并向用户返回适当的消息:此处回显的消息是jQuery将在Ajax调用的div“响应”中显示的消息。

Voilà: not too difficult, is it? And it works like a charm: add some css style to stylish the visible elements and you'll get a quick and easy way to implement a modern, Ajax email form. And overall, you can now easily add Ajax capabilities to your CodeIgniter site.

Voilà:不太困难,是吗? 它的工作原理就像一种魅力:添加一些CSS样式以使可见元素变得时尚,您将获得快速简便的方法来实现现代的Ajax电子邮件表单。 总体而言,您现在可以轻松地将Ajax功能添加到您的CodeIgniter站点。

翻译自: https://www.experts-exchange.com/articles/18451/Using-Ajax-in-CodeIgniter.html

使用codeigniter

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值