除了更换 div 之外,一切正常。当我使用 jquery 和 ajax 提交表单时,我的 php 将数据存储在数据库中,并创建一个需要放置在表单所在位置的新 div。但是当我提交表单时,它会放置被表单替换的 div。
Controller :
public function postStoryPanel(UpdateStoryRequest $request, $user_id)
{
$provider = new StoryProvider($user_id);
$panel[] = $provider->updateStoryByUserId($request, $user_id);
return Response::json($panel);
}
故事提供者:
// This just stores the data in the database and it wil trigger the method
// for creating the div with the data from database
public function updateStoryByUserId($request, $user_id)
{
$story = User::findOrFail($user_id)->story->last();
if(is_null($story)) {
$story = new Story();
$story->bio_id = Bio::firstOrCreate(['user_id' => $user_id])->id;
$story->title = $request->get('title');
$story->body = $request->get('body');
$story->save();
}else{
$story->delete();
$story = new Story();
$story->bio_id = Bio::where('user_id', $user_id)->first()->id;
$story->title = $request->get('title');
$story->body = $request->get('body');
$story->save();
}
return $this->getStoryPanelByUserId($user_id);
}
// This will create the div with the data from database
public function setEditStoryPanelByUserId($user_id)
{
return $this->storyPanel = new StoryPanel(
$user_id,
$this->setEditHeaderContent($user_id),
$this->setEditBodyContent($this->story),
$this->setEditFooterContent($user_id)
);
}
JQuery 和 Ajax:
function postRoute(route, form_id)
{
$.ajax({
type: "POST",
url: route ,
data: $('#'+form_id).serialize(),
dataType: 'json',
success: function (data) {
placePanel(data);
}
});
}
function placePanel(data){
var response = '';
if(data.length > 1){
response = 'multi';
}else{
response = 'single';
}
var panels = [];
var panel_id = [];
if(response == 'multi'){
for(var i = 0; i < data.length; i++){
panels[i] = renderPanel(data[i]);
panel_id[i] = data[i]['panel_id'];
}
}else{
panels[0] = renderPanel(data[0]);
panel_id[0] = data[0]['panel_id'];
}
for(var x = 0; x < panels.length; x++){
injectPanel(panels[x], panel_id[x]);
}
}
function renderPanel(panelObj)
{
var panel = "";
for(var key in panelObj){
if(panelObj[key] != null) {
console.log(panelObj[key]);
if(key != 'panel_id'){
panel += panelObj[key];
}
}
}
return panel;
}
function injectPanel(panel, panel_id)
{
var found_panel = document.getElementById(panel_id);
if(found_panel != null){
$('#'+panel_id).replaceWith(panel);
}else{
$('#bio').append(panel);
}
}
希望我的问题得到了很好的阐述。 请原谅我的(糟糕的)英语,我的主要语言是荷兰语。
最佳答案
我发现我的代码有问题。当我创建一个新的 StoryProvider($user_id) 时,我从数据库中获取 div
的数据。
这就是为什么我得到旧的 div 而不是新的。
现在,当触发创建 div 的方法时,我从数据库获取数据。
关于javascript - 我得到了一个带有来自服务器的数据的div,使用ajax,div将被替换为我使用jquery和ajax提交到php路由的表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30593945/