![](/img/trans.png)
[英]I have successfully loaded a form into a <div> element using jQuery $.Ajax. I need to know how to submit that form using jQuery Ajax
[英]I got a div with data from the server, with ajax the div will be replaced with a form that i submit with jquery and ajax to a php route
除更換div之外,一切正常。 當我使用jquery和ajax提交表單時,我的php將數據存儲在數據庫中,並創建了一個新的div,需要將其放置在表單所在的位置。 但是,當我提交表單時,它將放置被表單替換的div。
控制器:
public function postStoryPanel(UpdateStoryRequest $request, $user_id)
{
$provider = new StoryProvider($user_id);
$panel[] = $provider->updateStoryByUserId($request, $user_id);
return Response::json($panel);
}
StoryProvider:
// 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),
我從__construct
中獲取了來自div
的數據庫中的數據。 這就是為什么我得到舊div而不是新div的原因。
現在,當觸發該方法將創建div時,我將從數據庫中獲取數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.