我使用JQuery访问一些数据和一个PHP文件在WWW文件夹的localhost。我发送id到php文件,我想要一些关于id的细节。
当我使用这个代码在英特尔XDK。然后它在移动视图中显示完美,但在浏览器中不工作。
任何形式的帮助都将是感激的。
index . html
<!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">
<head>
<title>jQuery PHP Json Response</title>
<style type="text/css">
div
{
text-align:center;
padding:10px;
}
#msg {
width: 500px;
margin: 0px auto;
}
.members {
width: 500px ;
background-color: beige;
}
</style>
</head>
<body>
<div id="msg">
<table id="userdata" border="1">
<thead>
<th>Id</th>
<th>Latitude</th>
<th>Longitude</th>
</thead>
<tbody></tbody>
</table>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var result = prompt("Enter a address");
$.post("http://localhost/getuser.php", { str : result }, function(json) {
alert(json);
$.each($.parseJSON(json), function(idx, obj) {
alert(obj.id);
var tblRow =
"<tr>"
+"<td>"+obj.id+"</td>"
+"<td>"+obj.lat+"</td>"
+"<td>"+obj.lng+"</td>"
+"</tr>" ;
$("#userdata tbody").append(tblRow);
});
});
});
</script>
</body>
</html>
在WWW文件夹getuser.php
<?php
$host="localhost"; //replace with your hostname
$username="root"; //replace with your username
$password="auroin"; //replace with your password
$db_name="map"; //replace with your database
// $str = $_REQUEST['str'];
$str = $_POST['str'];
//$str = 1;
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from pet where id='".$str."'"; //replace emp_info with your table name
$result = mysql_query($sql);
$json = array();
while($row=mysql_fetch_object($result)){
$json[] = $row;
}
mysql_close($db_name);
//echo '{"members":'.json_encode($json).'}';
echo json_encode($json);
// please refer to our PHP JSON encode function tutorial for learning json_encode function in detail
?>
编辑:-
一些错误是我得到在我的控制台…没有声明HTML文档的字符编码。在某些浏览器配置中,如果文档包含US-ASCII范围以外的字符,则文档将以乱码文本呈现。页的字符编码必须在文档或传输协议中声明。index.html
跨域请求阻塞:同源策略禁止读取getuser.php的远程资源。这可以通过将资源移动到相同的域或启用CORS来解决。getuser.php
我建议您在浏览器中禁用同源策略,以便测试来自本地文件的跨域AJAX请求。
例如,使用Windows上的Google Chrome,您可以通过使用以下命令启动Chrome来禁用此策略:
C:'Users'YOUR_USER'AppData'Local'Google'Chrome'Application' Chrome .exe—allow-file-access-from-files—disable-web-security
结合起来,这两个标志将允许您测试来自本地文件的跨域ajax请求