Zend框架2使用AJAX [英] Using ajax in zend framework 2

查看:126
本文介绍了Zend框架2使用AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是真正的新Zend框架2和Web应用程序。在我的应用程序,我想有一个按钮,触发了更改数据库的内容,并返回一个字符串,我可以用它来更新网站上的可见内容的功能。由于我不想要的网站被点击该按钮时重新加载,我想做到这一点使用AJAX。读了几个AJAX的教程后,我想到的是,该解决方案看起来somilar这样:

i am really new to the zend framework 2 and to the programming of web applications. In my application, i want to have a button which triggers a function that changes the content of a database and returns a String which i can use to update the visible content of the website. As i don´t want the website to reload when the button is clicked, i would like to do this using ajax. After reading a couple of ajax tutorials, i imagined that the solution would look somilar to this:

的HTML部分:

 <head>

 <script type="text/javascript">

 function myFunction() {

var xmlhttp = new XMLHttpRequest();
    // I am working with Chrome

    xmlhttp.onreadystatechange=function(){

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){

                var text = xmlhttp.responseText;
        document.getElementById("text_paragraph").innerHTML =                 
                            text;
            }
                    };

        xmlhttp.open("GET", "function.php", true);
        xmlhttp.send();

}

 </script>

 </head>

 <body>
 ......
 <button id="function_button" onClick="myFunction()">Click</button>
 <p id = "text_paragraph">Initial text"</p>
 ......  
 </body>

随着PHP文件function.php(为始,我只是希望它返回一个文本值):

With the .php file function.php (for the beginning, i just want it to return a text value) :

<?php

     echo "Text triggered by the button click";
?>

当我尝试测试按钮,没有任何反应。显然,xmlhttp.status是404和function.php文件不容找到。我想,无论是位置,我把function.php文件(它是在同一文件夹中文件使用.phtml作为 - 网站查看文件)或使用在xmlhttp.open网址i'm - 功能是错误的。你能告诉我如何在ZF2正确使用AJAX?感谢您的时间,每一个答案是非常AP preciated。

When i try to test the button, nothing happens. Apparently, the xmlhttp.status is 404 and the function.php file can´t be found. I suppose that either the location where i put the function.php file (it is in the same folder as the .phtml - view file of the website) or the url i´m using in the xmlhttp.open - function is wrong. Could you please tell me how to use ajax in zf2 correctly? Thank you for your time, every answer is very much appreciated.

推荐答案

首先,我要感谢所有的答案的。他们真的是有很大的帮助。使用jQuery的确是更舒适,而不是只针对Ajax调用,比用纯Java脚本。詹姆斯,非常感谢你的回答。我试图使用它,但我可能是做错了什么事,因为它没有工作。我发现我的问题,另一种解决方案,我想它张贴在这里为了圆这个问题了。

First of all i want to thank for all your answers. They really were a great help. Using jQuery is indeed much more comfortable, and not only for Ajax calls, than using pure Javascript. James, thank you very much for your answer. I tried to use it, but i probably did something wrong because it did not work. I found another solution for my problem and i want to post it here in order to round this question up.

在code,我要张贴的是,只是做一个简单的事情一个小例子:对由Zend框架2,创建一个网站,一个按钮,用户点击,输入字段被读取,内容它被转移到一个服务器的功能,其中,根据接收到的数据,返回某一结果。接收结果后,该网站没有被重新加载更新。

The code that i am going to post is a little example that just does a simple thing: on a user click on a button in a website created by zend framework 2, an input field is read, the content of it is transfered to a server function, which, according to the data it receives, returns a certain result. After receiving the result, the website is updated without being reloaded.

由于我要使用JSON对象进行了沟通,有必要通过添加以下$ C $克莱因的module.config.php以激活ZF2 JSON的策略:

As i am going to use Json objects for the communication, it is necessary to activate the Json strategies in zf2 by adding the following codeline to the module.config.php:

// module/Application/config/module.config.php

'view_manager' => array (
                'display_not_found_reason' => true,
                'display_exceptions' => true,
                'doctype' => 'HTML5',
                'not_found_template' => 'error/404',
                'exception_template' => 'error/index',
                'template_map' => array (
                        'layout/layout' => __DIR__ .   
'/../view/layout/layout.phtml',
                        'application/index/index' => __DIR__ . 
'/../view/application/index/index.phtml',
                        'error/404' => __DIR__ . 
'/../view/error/404.phtml',
                        'error/index' => __DIR__ . 
'/../view/error/index.phtml' 
                ),
                'template_path_stack' => array (
                        __DIR__ . '/../view' 
                ),
                'strategies' => array (            // Add
                                           // this
                        'ViewJsonStrategy' // line
                )

        ),

该网站(称为例如example.phtml)的视图文件将类似于此:

The view file of the website (called, for example example.phtml) will look similar to this:

<html>
<head>

<script
    src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script>

//Function,  activated by clicking the button

$("#trigger").click(function(){

    var text = $("#input_to_read").val();
    var myData = {textData:text};

    //The post using ajax
    $.ajax({
            type:"POST",
            // URL : / name of the controller for the site / name of the action to be                         
            //                                                 executed
            url:"/example/answer",
            data:myData,
            success: function(data){
                                   //The callback function, that is going to be executed 
                                   //after the server response. data is the data returned
                                   //from the server.

                                   // Show the returned text
                                   $("#answer").text(data.text);


                                    },
            failure(function(){alert("Failure!!");})


           });


});


</script>
</head>

<body>

<input id="input_to_read" type="text">
<button id="trigger">Klick</button>
<!-- The answer will be shown here. -->
<p id="answer"></p>
</body>
</html>

的服务器功能,即是要被点击按钮时被调用,被放置在控制器的网站(在这种情况下,ExampleController),可以是这样的:

The server function, that is going to be called when the button is clicked, is placed in the controller for the website (in this case, the ExampleController) and could look like this:

//Make sure to add this line to use Json objects
use Zend\View\Model\JsonModel;

....


public function answerAction(){

#read the data sent from the site
$text = $_POST['textData'];

#do something with the data

$text = $text . "successfully processed";

#return a Json object containing the data

$result = new JsonModel ( array (

                'text' => $text 
        ) );
return $result;
}

这篇关于Zend框架2使用AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆