我有一个相当旧的网站,我继承了它作为新职位的一部分 - 它是按照Laravel 4.1.*版本规范构建的。
我的问题是Response::json
响应中返回未定义的变量,使用标准 AJAX post 方法正确定义所有 CSRF 内容和 ajaxSetup((。
应用刀片.php
$.ajax({
type: 'POST', //This will always be a post method for the supplier chain check form.
url: 'supply-us/application', //URL endpoint for the post form method: we'll set this to the controller function we're targeting.
data: { 'companyName': values['companyName'] }, //This will carry the form data that is needed to be passed to the server.
success: function (response) {
console.log(response['companyName']); << THIS LINE RETURNS "undefined"
console.log(typeof response) << THIS LINE RETURNS string
},
error: function (response) {
console.log(response);
},
});
values['companyName'] 返回我在表单中输入的内容。上面的"响应"简单地回击了 html - 所以我认为我的路由可能在 AJAX url 参数中定义不正确或错误定义,也许?以下是两条适用的路线:
路线.php
Route::controller('supply-us/application', 'ApplicationController');
Route::post('supply-us/application', 'ApplicationController@processSupplierApplication');
应用控制器.php:
<?php
use IlluminateHttpRequest;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $request) {
if (Input::has('companyName')) {
$this->companyName = Input::get('companyName');
$data = [
'success': true,
'companyName': $this->companyName
];
return response()->json($data);
}
}
}
任何专业提示将不胜感激!
在发布或获取结果时检查控制器中缺少的内容通常我遵循
-
在刀片中.php
<.form> {{csrf_field((}}
<.输入类型="文本" 名称="公司名称".> <./form.>
删除点试试这个,它将帮助您在控制器中找到丢失的东西
在你的刀片中
<.input type="text" name="companyName" id="companyName".>
在你的阿贾克斯
var company = $('#companyName').val();
$.ajax({
type: 'POST',
url: 'supply-us/application',
data: { 'Company':company,'_token': '{{ csrf_token() }}' },
success: function (response) {
alert(data) // if this not work then try this alert(data.company)
},
error: function (response) {
console.log(response);
},
});
在控制器中
<?php
use IlluminateHttpRequest;
use IlluminateSupportFacadesInput;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $req) {
if (!$req->get('Company')==null) {
$company = $req->get('Company');
return response()->json($company);
}else{
$company="no input give";
return response()->json($company);
}
}
}