我无法使用Ajax连接到数据库,它甚至没有运行.php文件。我在控制台下检查这是错误
获取http://local.testing.info/connections/getTag.php?q=a 404(不是 实测值)
在调试下:
下面的xmlhttp = XMLHttpRequest {readyState:1,timeout:0,withCredentials:false,upload:XMLHttpRequestUpload,responseURL:"" ...}
是我的代码
HTML:
<div>
<form>
<div>
<input type="text" ng-model="person.name" placeholder="Name">
</div>
<div>
<input type="text" ng-model="person.age" placeholder="Age">
</div>
</form>
</div>
{{data}}
JS :
test.controller('formController', function($scope) {
$scope.$watchCollection('person', function(newVal){
if (window.XMLHttpRequest) {
var xmlhttp=new XMLHttpRequest();
} else {
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
$scope.data = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getTag.php?q="+newVal.name,true);
xmlhttp.send();
});
}
PHP:
$q=$_GET["q"];
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="123"; // Mysql password
$db_name="testing"; // Database name
// Connect to server and select databse.
$link = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name",$link)or die("cannot select DB");
$sql="SELECT * FROM testing.people WHERE name = '".$q."'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$name =$row['name'];
if($name == '' || empty($name)) {
echo "<b>ID not found.</b>";
} else {
echo "<b>".$name."</b>";
}
mysql_close($link);
请告知我哪里做错了?
答案 0 :(得分:0)
Angular为ajax提供了自己的http服务。 尝试:
test.controller('formController',($scope,$http) {
$scope.$watchCollection('person', function(newVal){
var url = "YOUR_AJAX_PHP_URL";
var req = {
method: 'POST',
url: 'http://example.com',
data: { test: 'test' }
}
$http(req).then(function(response){/* success code here */}, function(response){/* fail code here */});
});
});
参考:angular docs
编辑:根据评论中的请求更改了示例