这是我的PHP代码保存为db2.php
<?php
mysql_connect("mysql15.000webhost.com","a3189966_root","");
mysql_select_db("a3189966_pd");
$firstName = $_GET[firstName];
echo $firstName;
$q=mysql_query("SELECT * FROM people where first='$firstName'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
$json = json_encode($output);
echo($json);
mysql_close();
?>
这是我的html代码,jquery和json保存为index2.html
$("#myForm").submit(function(){
var postData = $(this).serialize();
$.ajax({
type: "GET",
dataType: "json",
data: $("#myForm").serialize(),
url: "db2.php",
success: function(data){
alert("processing now" + data);
$.each(data,function(i,item){
alert("processing each data now");
$('<li></li>').html(item.first + " " + item.last).appendTo('#data');
});
},
error: function(data){alert("failed"+data);}
});
return false;
});
<form id="myForm" method="GET" action="">
<input type="textbox" name="firstName" id="firstName">
<input type="submit" name="myButton" value="submit">
</form>
<ul id="data">
</ul>
在我执行下面的html代码后,它只会提示错误。 我检查了几个小时,我看不到任何错误,这个代码可以正确执行。 这是从php
返回的json对象[{"id":"1","first":"wen","last":"hao","age":"123"}]
答案 0 :(得分:1)
将dataType
从jsonp
更改为json
。
dataType: "json",
答案 1 :(得分:1)
ajax调用的错误回调可以带三个参数。第二个和第三个论点可以让你更好地了解出了什么问题。
第二个参数的可能值(除了null)是 “timeout”,“error”,“abort”和“parsererror”。当出现HTTP错误时 发生时,errorThrown接收HTTP状态的文本部分, 例如“未找到”或“内部服务器错误。”
为你的ajax调用试试这样的事情:
$.ajax({
type: "GET",
dataType: "json",
data: $("#myForm").serialize(),
url: "db2.php",
success: function(data){
alert("processing now" + data);
$.each(data,function(i,item){
alert("processing each data now");
$('<li></li>').html(item.first + " " + item.last).appendTo('#data');
});
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
if(errorThrown) {
alert(errorThrown);
}
}
});