假设我有 2 个 .php 文件:index.php 和 ajax.php
这是 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;
更新
这是 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"}
我在这里错了什么?
谢谢你的时间!