php 在 Cakephp 中通过 ajax 发送数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17504604/
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-08-25 13:01:49  来源:igfitidea点击:

sending data via ajax in Cakephp

phpajaxcakephpcakephp-2.0cakephp-2.1

提问by hellosheikh

i am new to cakephp and trying to send data from ajax to my controller action.. i have a popup model in which there is a input box ..i want to grab that value and send to controller without page refresh

我是 cakephp 的新手,并试图将数据从 ajax 发送到我的控制器操作.. 我有一个弹出模型,其中有一个输入框..我想获取该值并发送到控制器而不刷新页面

here is my code ..

这是我的代码..

 <a  class="button anthracite-gradient" onclick="openPrompt()">submit </a>

my javascript

我的 JavaScript

 function openPrompt()
{
var cancelled = true;

$.modal.prompt('Please enter a value:', function(value)
{

    $.ajax({
        type:"POST",

        url:"/cakephp/controller/action/",
        success : function(data) {
           alert(value); //value right now is in this variable ... i want to send this variable value to the controller

        },
        error : function() {
           alert("false");
        }
    });


    }, function()
   {

    });
    };
</script>

myController

我的控制器

 public function action(){
    if( $this->request->is('ajax') ) {
      $new = $this->request->data; 

        echo "ok"
        return;
    }
}

i want to first get the value here and then send the response to may ajax request

我想首先在这里获取值,然后将响应发送到可能的 ajax 请求

回答by M Khalid Junaid

Its simple post the value to the controller and do what you want , in ajax request bind the value in data:{value_to_send:value}and get in controller

它简单地将值发布到控制器并执行您想要的操作,在 ajax 请求中绑定值data:{value_to_send:value}并进入控制器

 function openPrompt()
{
var cancelled = true;

$.modal.prompt('Please enter a value:', function(value)
{

    $.ajax({
        type:"POST",
        data:{value_to_send:value}, 
        url:"/cakephp/controller/action/",
        success : function(data) {
           alert(data);// will alert "ok"

        },
        error : function() {
           alert("false");
        }
    });


    }, function()
   {

    });
    };
</script>

 public function action(){
    if( $this->request->is('ajax') ) {
     // echo $_POST['value_to_send'];
     echo   $value = $this->request->data('value_to_send');

     //or debug($this->request->data);
        echo "ok"
      die();
    }
   }

For more see accessing-post-data

有关更多信息,请参阅访问后数据

回答by Sadee

I will give you some example. In my case, list out book list as a smart search while typing on text box.

我会给你一些例子。就我而言,在文本框中键入时,将图书列表列为智能搜索。

$( ".selectBook" ).each(function(){
    $(this).keyup(function( event ) {
        var tri = $(this).val();
        var oPrnt = $(this).parents('.smartsearch');
        var str = '';
        if(tri.length > 2){
            $.ajax({
                type: "POST",
                url: "/utility/getbooks/",
                data: JSON.stringify({string: tri, activeonly:false}),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                   $.each(data, function(key, val) {
                                str += '<li id="a'+key+'" term="'+val+'" data-did="'+key+'">'+val+'</li>';
                    }); 
                    oPrnt.find("ul.result").html(str);
                },
                error: function (errormessage) {
                    oPrnt.find("ul.result").html('<li><b>No Results</b></li>');
                }
            });
            oPrnt.find("ul.result").slideDown(100);
        }

    });
});

And in the controller, action (getbooks Action in UtilityController in my case)

在控制器中,动作(在我的例子中 UtilityController 中的 getbooks 动作)

public function getbooks($string = '', $activeonly = true){

        $this->autoRender = false;

        if( $this->request->is('ajax') ) {
            $data = $this->request->input('json_decode');
            $string = $data->string;
            $activeonly = $data->activeonly;            
        }

        $aReturn = array();
        // ... fetch books data from DB goes here...
        $aResult = $this->Book->fetch('list');
        foreach($aResult as $r){
            if(isset($r['bookname'])){
                $aReturn[$r['id']] = $r['bookname'];
            }
        }            
        return json_encode($aReturn);
    }