我有http://visiting/blog
页面。
控制器包含action_index和add_index方法。 Action_index()
返回索引页。 Add_index()
调用模型的方法add_data()
,将数据从表单插入到数据库。
我需要使用 ajax-request 组织我的应用程序,该页面http://visiting/blog
提交表单后不刷新。
视图
$.ajax({
type: 'POST',
url: '???', --------------------------> What should URL contain?
data: $(this).serialize()
控制器
function action_add() {
$title = $this->cleanStr($_POST["title_field"]);
$text = $this->cleanStr($_POST["text_field"]);
if ($title!="" && $text!="") {
$this->model->add_data($title, $text);
} else {
throw new Exception("Data is empty");
}
}
型
public function add_data($title, $text) {
try {
$query="INSERT INTO post (title, text) VALUES('$title', '$text')";
self::$db->query($query);
} catch(Exception $e) {
echo $e->getMessage();
}
}
视图
它是一个带有 ajax-request 的完整 html 文件。我想处理表单,即页面不刷新并将数据发送到数据库。
<div class="blog">
<h1> Blog </h1>
<form onsubmit="return validate()" id="add_form">
<fieldset>
<legend>Add new post:</legend>
<label>Title:</label><br>
<input type="text" name="title_field" id="titlef">
<br>
<label>Text:</label>
<br>
<textarea name="text_field" id="textf"></textarea>
<br>
<input onclick="return validate(); return false" type="submit" value="Submit">
<input onclick="return resetclass()" type="reset" value="Reset">
</fieldset>
</form>
<div class="blogposts">
<div id='response'></div>
<?php
foreach ($data as $values) {
echo "<div class='"blog_item'">";
echo "<h4 class='"blog_item_title'">" . $values["title"] . "</h4>" .
"<div class='"blog_item_text'">" . $values["text"] . "</div>" .
"<div class='"blog_item_time'">" . $values["time"] . "</div>";
echo "</div>";
}
?>
</div>
</div>
<script>
$(document).ready(function(){
$('#add_form').submit(function(){
// show that something is loading
$('#response').html("<b style='"font-size:20px; margin:40px;'"'">Loading ...</b>");
$.ajax({
type: 'POST',
url: '???', ------------> What should be into url?
data: $(this).serialize()
})
.done(function(data){
// show the response
$('#response').html(data);
})
.fail(function() {
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});
</script>
URL 应该是要命中的控制器方法的路径。 您不必在 URL 中包含基本路径(但如果需要,可以)。 所以像这样:
url: "howeverYourStructureIs/Action_index",
点击方法 action_index()。你可以把ajax想象成"好像你要点击页面,但实际上并没有导航到那个页面"之类的事情。因此,无论您通常会使用该方法,您放入 ajax 调用中的 url 都是您输入的。
希望这有帮助