我是cakephp的新手并尝试将数据从ajax发送到我的控制器动作.. 我有一个弹出模型,其中有一个输入框..我想获取该值并发送到控制器没有页面刷新
这是我的代码..
<a class="button anthracite-gradient" onclick="openPrompt()">submit </a>
我的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;
}
}
我想先在这里获取值,然后将响应发送给may ajax request
答案 0 :(得分:3)
它简单地将值发布到控制器并执行您想要的操作,在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();
}
}
有关详情,请参阅accessing-post-data
答案 1 :(得分:1)
我会举一些例子。在我的情况下,在文本框中键入时列出书籍列表作为智能搜索。
$( ".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);
}
});
});
在控制器中,动作(在我的情况下,在UtilityController中使用getbooks Action)
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);
}