我正在升级一个旧的php项目到laravel 4项目。我有一个功能,从一个引导模式使用ajax添加公司数据。但是这段代码不适合我目前的laravel项目,因为我在这个文件上使用了mysql_connect和mysql_select_db。我已经测试过了,它仍然有效,但我想使用像companies.store这样的命名路由。我目前使用rest路由的项目,它的工作完美。这是我的旧代码与当前laravel项目的结合,顺便说一下,它实际上工作得很好。
create.blade.php
function addNewCompany(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser doesn't support ajax!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//txtMessage is used to show message returned from the ajaxRequest
document.getElementById('txtMessage').value = ajaxRequest.responseText;
}
}
var companyName = document.getElementById('txtCompanyName').value;
ajaxRequest.open('POST', '{{ URL::asset("assets/query/saveCompany.php") }}');
ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxRequest.send("companyName=" + companyName);
}
saveCompany.php//我放置在公共/assets/query文件夹
<?php
$companyName = $_POST["companyName"];
$con=mysql_connect("localhost","root","");
mysql_select_db("dbname", $con);
$sql = "INSERT INTO `companies` (`companyName`)
VALUES ('$companyName')";
$result = mysql_query($sql, $con);
if($result)
{
echo "Company added successfully";
}
else
{
echo mysql_error();
}
?>
与其将ajax请求发送到saveCompany.php文件,不如将请求发送到company.store.
首先,您必须在app/config/database.php
文件中配置数据库连接。
Route::controller('companies', 'CompanyController');
模型/Company.php
<?php
class Company extends Eloquent{
protected $table = 'companies';
protected $guarded = [''];
}
控制器/CompanyController.php
<?php
class CompanyController extends Controller {
public function getAddCompany(){
return View::make('create');
}
public function postCompany(){
$company = new Company(Input::all());
$company->save();
return Redirect::action('CompanyController@getAddCompany');
}
}
create.blade.php
function addNewCompany(){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser doesn't support ajax!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//txtMessage is used to show message returned from the ajaxRequest
document.getElementById('txtMessage').value = ajaxRequest.responseText;
}
}
var companyName = document.getElementById('txtCompanyName').value;
ajaxRequest.open('POST', '{{ URL::action("CompanyController@postCompany") }}');
ajaxRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxRequest.send("companyName=" + companyName);
}