假设我有2个PHP文件:index.php文件和ajax.phpjson_encode犯规响应正确的JSON数据
这是index.php文件:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Website title</title>
<link href="css.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script type="text/javascript">
ajax_register = function(){
$.ajax({
type: "post",
url: 'ajax.php',
dataType: 'json',
data: "act=register",
success: function(data){
//var json = $.parseJSON(data);
//alert(json);
alert(data.result);
},
error: function(e){
alert("Error : " + e);
}
});
};
</script>
<form name="myForm" id="myForm" method="post">
Your name :
<input type="text" name="name" id="name" />
<a href="javascript:void(0)" onclick="ajax_register()">Register</a>
</form>
</body>
</html>
这是ajax.php:
<?php
$result = array("result"=>"Success");
echo json_encode($result);
exit;
但我总是有“错误”警报对话框。
看看Firebug,我看到响应数据包含所有html元素,而不是仅包含json数据。
尝试通过编辑ajax.php发送标题为 “JSON”:
<?php
header("Content-type: application/json");
$result = array("result"=>"Success");
echo json_encode($result);
exit;
但它不工作。响应标题总是:Content-Type:text/html;
UPDATE
这是ajax.php响应:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Website title</title>
<link href="css.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<script type="text/javascript">
ajax_register = function(){
$.ajax({
type: "post",
url: 'ajax.php',
dataType: 'json',
data: "act=register",
success: function(data){
//var json = $.parseJSON(data);
//alert(json);
alert(data.result);
},
error: function(e){
alert("Error : " + e);
}
});
};
</script>
<form name="myForm" id="myForm" method="post">
Your name :
<input type="text" name="name" id="name" />
<a href="javascript:void(0)" onclick="ajax_register()">Register</a>
</form>
{"result":"Success"}
什么我错在这里?
谢谢你的时间!
什么是错误的响应HTML元素?它是您认识的HTML(您是否写过),还是来自Web服务器返回的错误页面?错误回调完全被使用表明你得到的不是来自服务器的200响应 –
也许以前的响应被'$ .ajax'缓存。尝试将'cache'选项设置为'false'。然后重新启动浏览器。 – flowfree
如果您直接在浏览器中打开ajax.php网址,该怎么办? –