传递数据从视图到控制器使用AJAX
问题描述:
我想发送一些数据按钮点击一个控制器,并显示在视图中的内容股回应。但是,我在将数据发送到控制器时遇到问题。这里就是我想要做的事:传递数据从视图到控制器使用AJAX
test.php的
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$.ajax({
type: 'GET',
url: 'get-response',
dataType: 'json',
data: {
"id": "1"
},
success: function(response){
$('#content').html(response.first);
}
});
});
$("#btn2").click(function(event){
$.ajax({
type: 'GET',
url: 'get-response',
dataType: 'json',
data: {
"id": "2"
},
success: function(response){
$('#content').html(response.first);
}
});
});
});
</script>
<input type="button" id="btn1" value="Button1 Content" />
<input type="button" id="btn2" value="Button2 Content" />
<br>
<div id="content"></div>
route.php
Route::get('ajax-example', function(){
return View::make('test');
});
Route::get('get-response/{id}', array('as'=>'get-response', 'uses'=>'[email protected]'));
AjaxController.php
public function getResult($id){
if($id==1){
$content = "Hello";
}
else if($id==2){
$content = "World";
}
return Response::json(array('first'=>$content));
}
错误 任何人都可以请帮我在这里。我现在有点困惑。谢谢:)
答
行,所以我想我想通了什么造成的问题。
我改变了我的路线
Route::get('get-response', array('as'=>'get-response', 'uses'=>'[email protected]'));
和控制器我加入
public function getResult(){
$id = $_GET['id'];
现在,它似乎工作得很好:)
+0
在你的Laravel控制器中,你应该使用$ id = Input :: get('id'); – 2015-02-09 08:47:26
答
,如果你需要得到的参数做到这一点,
Input::get('id');
和路线
Route::get('get-response', array('as'=>'get-response', 'uses'=>'[email protected]'));
,因为你的Ajax请求是一样的东西,host/get-response?id=5
这是不兼容Route::get('get-response/{id}'..
,因为这条路线需要类似host/get-response/5
另一种方式,你可以保持您的路线为u申报并改变Ajax请求的URL,
$.ajax({
type: 'GET',
url: 'get-response/'+1,
dataType: 'json',
data: {},
success: function(response){
$('#content').html(response.first);
}
});
你能不能改变这一行网址:“GET-响应'到网址:'get-response/2'然后尝试?并删除Ajax中的数据配置属性? – Asik 2015-02-09 06:32:54
感谢您回复@Asik,但我想我找到了解决方案。我没有正确处理url查询字符串。所以我只是加了$ id = $ _GET ['id'];并解决了这个问题:) – 8yt3c0d3 2015-02-09 06:48:15