Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在zend framework 2中使用ajax_Javascript_Ajax_Zend Framework2 - Fatal编程技术网

Javascript 在zend framework 2中使用ajax

Javascript 在zend framework 2中使用ajax,javascript,ajax,zend-framework2,Javascript,Ajax,Zend Framework2,我对zend framework 2和web应用程序编程非常陌生。在我的应用程序中,我希望有一个按钮,该按钮触发一个函数,该函数更改数据库的内容并返回一个字符串,我可以使用该字符串更新网站的可见内容。由于我不希望在单击按钮时重新加载网站,因此我希望使用ajax来完成此操作。在阅读了几篇ajax教程后,我认为解决方案与以下内容非常相似: <html> <head> <script src="http://ajax.googleapis.com/ajax/li

我对zend framework 2和web应用程序编程非常陌生。在我的应用程序中,我希望有一个按钮,该按钮触发一个函数,该函数更改数据库的内容并返回一个字符串,我可以使用该字符串更新网站的可见内容。由于我不希望在单击按钮时重新加载网站,因此我希望使用ajax来完成此操作。在阅读了几篇ajax教程后,我认为解决方案与以下内容非常相似:

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

函数myFunction(){
var xmlhttp=new XMLHttpRequest();
//我在和Chrome合作
xmlhttp.onreadystatechange=函数(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
var text=xmlhttp.responseText;
document.getElementById(“文本\段落”)。innerHTML=
文本;
}
};
open(“GET”,“function.php”,true);
xmlhttp.send();
}
......
点击
初始文本

......
对于.php文件function.php(首先,我只希望它返回一个文本值):



当我尝试测试按钮时,什么也没有发生。显然,xmlhttp.status是404,而function.php文件找不到。我假设我放置function.php文件的位置(它与网站的.phtml-view文件位于同一文件夹中)或者我在xmlhttp.open-函数中使用的url是错误的。您能告诉我如何在zf2中正确使用ajax吗?谢谢您的时间,我非常感谢您的每一个回答。

通常我处理这个问题的方法是构建一个RPC控制器,只返回JSON,然后使用一些好的javascript框架,例如,和,来生成以逻辑方式更新相关UI区域。我相信基本Zend controller类提供了一个
$this->\u helper->json
方法,该方法将返回json,而不是返回您在给定视图中定义的内容。在下面的
Public\u RpcController
中,我甚至没有定义视图。它返回json,我可以结合使用使用JS框架进行客户端标记操作。使用JS框架有一点学习经验,但很值得学习

class Public_RpcController extends MySubClassed_Controller_Action
{
    public function getUserDataAction()
    {
        $output = array();
        $request = $this->getRequest();

        ...

        $output = array(
                'Value1'    => "foobar",
                'Value2'    => "foobar",
        );
        return $this->_helper->json($output);       
    }   
}

// Use Jquery to fetch JSON data to update. 
$.getJSON( "/rpc/get-user-data", function( data ) { 
    // Do something with the JSON data like bind to Knockout template.
});

首先,我要感谢你的回答。他们真的帮了我很大的忙。使用jQuery确实比使用纯Javascript更舒服,而且不仅仅是Ajax调用。James,非常感谢你的回答。我尝试过使用它,但我可能做了一些错误,因为它不起作用。我为我的问题找到了另一个解决方案我和m想把它贴在这里,以便把这个问题归纳起来

我将要发布的代码是一个小例子,它只做了一件简单的事情:用户点击zend framework 2创建的网站中的按钮,就会读取一个输入字段,将其内容传输到一个服务器函数,该函数根据接收到的数据返回一个特定的结果。在接收到结果后,网站将被升级在没有重新加载的情况下重新加载

由于我将使用Json对象进行通信,因此有必要通过向module.config.php添加以下代码行来激活zf2中的Json策略:

// 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
                )

        ),
网站的视图文件(例如称为.phtml)将类似于以下内容:

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

您有html语法错误

Initial text

您说得对,谢谢qisho。您应该查看它,它将大大简化您的ajax请求。另外,请查看使用Firefox的FireBug之类的调试工具或使用Chrome/Safari中的开发人员工具。您还应该查看主干。js谢谢您的回答。如果你不介意的话,我还有一些问题要问。我可以将getUserDataAction()写入我正在为站点使用的控制器中,并使用jQuery Ajax post调用它吗?还是必须编写一个额外的控制器?我是否将$.getJSON代码行放入jQuery Ajax post的回调函数中?这是一篇很好的解决方案一步一步的描述。我知道这是一篇老文章,但不使用
$\u post
,ZF2已经过滤了您可以从
$this->params()->fromPost('param name')
//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;
}