使用AJAX从Laravel中的数据库中检索数据

时间:2014-08-07 03:02:43

标签: ajax dynamic drop-down-menu laravel

嗯,我是laravel的新手。如果有人可以帮助我解决这个问题,它可以为我解释很多。我想要做的是将这个PHP ajax请求转换为laravel ajax。这是一个动态选择框。

PHP和ajax代码是:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Sections Demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;

$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
} 
});

});
});
</script>
<style>
label
{
font-weight:bold;
padding:10px;
}
</style>
</head>

<body>
<div style="margin:80px">
<label>Country :</label> <select name="country" class="country">
<option selected="selected">--Select Country--</option>
<?php
include('db.php');
$sql=mysql_query("select id,data from data where weight='1'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$data=$row['data'];
echo '<option value="'.$id.'">'.$data.'</option>';
 } ?>
</select> <br/><br/>
<label>City :</label> <select name="city" class="city">
<option selected="selected">--Select City--</option>

</select>



</div>
</body>
</html>

这是city.php以及从数据库中检索信息的地方

<?php
include('db.php');
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysql_query("select b.id,b.data from data_parent a,data b where b.id=a.did and parent='$id'");

while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$data=$row['data'];
echo '<option value="'.$id.'">'.$data.'</option>';

}
}

?>

这就是我想在laravel中做的,我得到一个错误号500

我的控制器(RegistrationController):

public function city()
    {
        $city= City::all();
        return View::make('country', ['city'=>$city]);
    }

我的路线

Route::post('/contry/city', 'RegistrationController@city');

我在Laravel的Ajax

$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;

$.ajax
({
type: "POST",
url: "/country/city",
data: dataString,
cache: false,
dataType : "html",
success: function(html)
{
$(".stage").html(html);
} ,
// code to run if the request fails; the raw request and
    // status codes are passed to the function
    error: function( xhr, status, errorThrown ) {
        alert( "Sorry, there was a problem!" );
        console.log( "Error: " + errorThrown );
        console.log( "Status: " + status );
        console.dir( xhr );
    },

    // code to run regardless of success or failure
    complete: function( xhr, status ) {
        alert( "The request is complete!" );
    }
});

});

0 个答案:

没有答案