【发布时间】:2014-11-02 21:08:16
【问题描述】:
我正在创建一个包含表单的模式框。一旦使用 ajax 和 php 提交,表单将返回输入,然后模式框应该消失。问题是虽然结果显示了几秒钟,然后框消失并且页面刷新。
<button class="toggleModal">trigger iModal</button>
<div class="modal">
<header>
<h2>Other Symptoms</h2>
<i class="fa fa-times close toggleModal"></i>
</header>
<section>
<form class="js-ajax-php-json" method="post" accept-charset="utf-8">
<textarea name="textareathebeast" row="4" cols="40" placeholder="some text"></textarea><br>
<input class="modalSubmit" type="submit" name="submit" value="submit">
</form>
</section>
</div>
<div class="the-return">
[HTML is replaced when successful.]
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
>
$(function(){
$('.toggleModal').on('click', function (e) {
$('.modal').toggleClass('active');
});
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(data) {
$(".the-return").html(
"Text Message: " + data["textareathebeast"]
);
}
});
return true;
});
});
</script>
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test(){
$return = $_POST;
//Do what you need to do with the info. The following are some examples.
//if ($return["favorite_beverage"] == ""){
// $return["favorite_beverage"] = "Coke";
//}
//$return["favorite_restaurant"] = "McDonald's";
$return["json"] = json_encode($return);
echo json_encode($return);
}
?>
【问题讨论】: