gpt4 book ai didi

php - 如何将 View 发送回 Laravel 中的 ajax

转载 作者:行者123 更新时间:2023-12-01 04:37:23 25 4
gpt4 key购买 nike

我是 Laravel 新手。我创建了一个表单,当用户单击提交按钮时,我进行 ajax 调用并将数据保存到数据库中的表中。到这里为止一切都工作正常。保存数据后,我将进行另一个 ajax 调用来显示最近保存的信息。现在,当我尝试在 View 中呈现数据时,出现异常 {"readyState":4,"responseText":"{\n\"message\":\"尝试获取非对象的属性(查看:D:\\\\xampp\\\\htdocs\\\\用户信息\\\\资源\\\\ View \\\\ajax\\\\show.blade.php)

如果我在不使用ajax的情况下执行相同的操作,它工作得很好。

路线:

//route for ajax call to display user information
Route::get('/userinfo','ClientsController@ajaxShow');

Controller

public function ajaxShow(Client $client){
$userID=Input::get('id');
$user=Client::find($userID);
$msg='Your data is saved.Go to listing page to see.';
$returnHtml=view('ajax.show',compact('msg'))->with('user',$user)->render();
return $returnHtml;
}

型号

class Client extends Model
{
protected $fillable=[
'name',
'prov_id',
'telephone',
'postal',
'salary'
];
use SoftDeletes;

//client/users table can have many provinces.
public function province(){
return $this->belongsTo('App\Province','prov_id');
}
protected $table='users';
protected $dates=['deleted_at'];
}

查看

<div class="alert alert-primary">
{{$msg}}<br/>
</div>
<div>
{{$user}}

</div>

<div class="info_wrapper">
Name:{{$user->name}}<br/>
Province :{{$user->prov_id->name}}<br/>
Telephone :{{$user->telephone}}<br/>
Postal:{{$user->postal}}<br/>
Salary:{{$user->salary}}
</div>

当我在不使用 ajax 的情况下执行相同的操作时,它工作得很好。

路线

Route::get('/testuserinfo','ClientsController@testShow');

Controller

public function testShow(Client $client){
$user=Client::find(293);
$msg='Your data is saved.Go to listing page to see.';
return view('clientinfo.show',compact('user','msg'));
}

查看

<div class="alert alert-primary">
{{$msg}}<br/>
</div>

<div class="info_wrapper">
Name:{{$user->name}}<br/>
Province :{{$user->province->name}}<br/>
Telephone :{{$user->telephone}}<br/>
Postal:{{$user->postal}}<br/>
Salary:{{$user->salary}}
</div>

Ajax

$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

//when the user clicks on save button call ajax to save user information
$('#frmSaveUser').on('submit',function(e){
e.preventDefault();

var clientName=$.trim($("input[name='name']").val());
var province=$("input[name='prov_id']").val();//$("#_province").val();
var tel=$.trim($("input[name='telephone']").val());
var postal=$.trim($("input[name='postal']").val());
var salary=$.trim($("input[name='salary']").val());


if(validateInputFields(clientName,province,tel,postal,salary)){
$.ajax({
method:'POST',
url:$(this).attr('action'),
data:$(this).serialize(), //get all the input field values
dataType:'json'})
.done(function(res){
//todo
// console.log('res:'+JSON.stringify(res));
showUserInformation(res.id)
})
.fail(function(res){
if(res.status!==422){
//alert('Error saving your work.');
$('#frmSaveUser').find('.error').remove();//remove any previous errors displayed
console.log(res);
return;
}
else{

$('#frmSaveUser').find('.error').remove();
//parse the response text and and get the errors
var errors=JSON.parse(res.responseText);
// console.log(errors);
for(var fieldName in errors['errors']){
//console.log(errors['errors'][fieldName]);
var inputField=$('#frmSaveUser').find('[name='+fieldName+']').parent(); // find the parent element of the input that has error
//if there are more than one error message create a list by concatenating errors in msg var.
var msg='<ul>';
for(var i=0;i<errors['errors'][fieldName].length;i++ ){
msg+='<li>'+errors['errors'][fieldName][i]+'</li>';
}
msg+='</ul>';

inputField.after().append('<div class="error">'+msg+'</div>');//display the error message below the field.
}

}
});//end of ajax method
}//end of if statement
});//end of form submit function

上面的ajax从done()函数调用的函数

/*Function to display recently inserted user's information*/
function showUserInformation(id){
console.log('id:'+id);
$.ajax({
method:'GET',
url:'./userinfo',
data:{id:id}
})
.done(function(data){
console.log(JSON.stringify(data));
console.log(data);
$('.container-fluid').empty().html(data);
})
.fail(function(res){
console.log(JSON.stringify(res));
})//end of ajax method
}

如果有人能帮助我解决这个问题,我将不胜感激。预先感谢您。

最佳答案

保存信息后无需再次进行 Ajax 调用。保存时只需从 Controller 以 JSON 形式返回新用户信息即可。然后你可以解析 AJAX .done 部分中的 JSON 并在你需要的地方显示。

关于php - 如何将 View 发送回 Laravel 中的 ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48071950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com