[英]Submitting a form through AJAX using CodeIgniter
我正在構建一個Web應用程序,它將使用戶可以Q&A格式關注討論線程。 為此,在顯示問題時,每個問題旁邊都有一個“關注”按鈕。 我希望用戶能夠在不重新加載頁面的情況下遵循這些線程,從而使用AJAX。 因此,我希望AJAX調用:
1)提交更新記錄以下關系的數據庫的表格; 和2)將“關注”提交按鈕替換為“關注”
這是我的JavaScript代碼:
$("#submitFollow").click(function() {
var type = $("input#type").val();
var u_id = $("input#u_id").val();
var e_id = $("input#e_id").val();
var dataString = 'type='+ type + '&u_id=' + u_id + '&e_id=' + e_id;
$.ajax({
type: "POST",
url: "<?=site_url()?>/follow/ajaxFollow",
data: dataString,
success: function() {
$('#following').html("Following");
.hide()
.fadeIn(1500)
}
});
return false;
});
});
這是我的表單代碼的樣子。 我刪除了操作和方法,以防止表單定期提交。 我試圖使用JS阻止Default,但是那沒用。 (值由模型填充):
<div id="following">
<form id="followForm" action="" method="">
<input type="hidden" name="type" id="type" value="question">
<input type="hidden" name="u_id" id="u_id" value="1">
<input type="hidden" value="12" name="e_id" id="e_id">
<input type="submit" id="submitFollow" value="Follow Question" class="submitFollow">
</form>
</div>
現在,控制器非常簡單-只需獲取post變量數組並將其直接提交到數據庫即可。
我不太擅長JavaScript,因此,如果我花了很多時間解決一個簡單的問題,我深表歉意。
我這里只是一般性的,但希望會有所幫助。 如果是我,我將執行以下操作:
這是從codeigniter生成的一些html:
<div>
questions 1
</div>
<div>
<a class="follow" href="http://example.com/follow/question/1">Follow Question 1</a>
</div>
<div>
questions 2
</div>
<div>
<a class="follow" href="http://example.com/follow/question/2">Follow Question 2</a>
</div>
然后,使所有內容都無需使用javascript(稍后再添加)。 所以這是帶有一些通用代碼的codeigniter控制器:
<?php
class Follow extends Controller {
function Follow()
{
parent::Controller();
$this->auth->restrict_to_admin();
}
function question($id = NULL)
{
if($id)
{
//get question from database using the id
//i assume somehow the user is logged in? use their id where applicable
echo '<span>You are now following this question</span>';
}
}
}
/* End of file follow.php */
現在,無論他們是否使用javascript,它都可以使用。 在這里添加javascript(我假設您正在使用jquery?)。 如果沒有,它將足夠接近。
$(document).ready(function(){
$('follow').click(function(event){
event.preventDefault();
var followUrl = $(this).attr('href');
//do ajax call here.
$.post(
followUrl,
{
//any paramaters you need to add can
//go here in this format:
//param_key: param_value
},
function(responseText){
//here you can update the clicked link to say something
//like "you are now following this question"
//the responseText var will have whatever text the server responds with.
//just responsd with html
},
'html'
);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.