【发布时间】:2015-05-04 18:44:49
【问题描述】:
我已经尝试了本教程http://labs.jonsuh.com/jquery-ajax-php-json/,但它不起作用,我完全按照方向进行了操作。我认为这是因为return.php。
index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$("document").ready(function(){
$(".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) {
$(".return").json(
"Favorite beverage: " + data["favorite_beverage"] + "<br />Favorite restaurant: " + data["favorite_restaurant"] + "<br />Gender: " + data["gender"] + "<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
</head>
<body>
<form action="return.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
<input type="text" name="favorite_beverage" value="" placeholder="Favorite restaurant" />
<input type="text" name="favorite_restaurant" value="" placeholder="Favorite beverage" />
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<input type="submit" name="submit" value="Submit form" />
</form>
<div class="return">
[HTML is replaced when successful.]
</div>
</body>
</html>
response.php
<?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_function(); 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_function(){
$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);
}
?>
【问题讨论】:
-
如果您检查控制台,您会确切地看到问题出在哪里,是 JS 错误停止发送请求,还是 PHP 错误意味着响应没有返回。
-
我多次尝试将return.php更改为response.php。还是不行
-
您正在在实际服务器上运行这一切,对吧?在您打开
<?php标记error_reporting(E_ALL); ini_set('display_errors', 1);后立即将错误报告添加到文件顶部 -
它是否真的在浏览器的开发者工具部分发出 ajax 请求。如果不是,那将是客户端问题。如果它正在发出请求,那么您应该死在 response.php 中的线程上
-
@JayBlanchard 是的,我在本地主机上运行它。我尝试了错误报告,但它什么也没做。