Javascript 通过http请求从变量检索数据
我不熟悉http请求和php。我有一个http:Javascript 通过http请求从变量检索数据,javascript,php,ajax,xmlhttprequest,Javascript,Php,Ajax,Xmlhttprequest,我不熟悉http请求和php。我有一个http: xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var doc = xmlhttp.response; myFunc(doc); } }; xmlhttp.open("GET",some.php",true); xm
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var doc = xmlhttp.response;
myFunc(doc);
}
};
xmlhttp.open("GET",some.php",true);
xmlhttp.responseType = "document";
xmlhttp.send(null);
php文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body id="idk">
<?php
include("include1.inc");
include_once("include2.inc");
$cxn = mysqli_connect($host,$user,$passwd,$dbname) or die("Could not connect to the server at this time.");
$table = 'table';
$data = retrieveData($table, $cxn);//selects data from mysql db return array
var_dump($data);
?>
</body>
</html>
如何从数据库中获取保存数组的数据变量?
当我转储或打印变量时,数组被传递到`responseText。有没有更雄辩的方法来抓住这个阵列 您将响应类型设置为“document”,因此您将在对象上获取HTMLDocument作为响应。因此,如果您只需要获取数据变量,请尝试通过以下方式更改代码: javascript:
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var doc = xmlhttp.response;
myFunc(doc);
}
};
xmlhttp.open("GET","some.php",true);
xmlhttp.responseType = "json";
xmlhttp.send();
和php:
<?php
include("include1.inc");
include_once("include2.inc");
$cxn = mysqli_connect($host,$user,$passwd,$dbname) or die("Could not connect to the server at this time.");
$table = 'table';
$data = retrieveData($table, $cxn);//selects data from mysql db return array
echo json_encode($data);
?>
请注意,在本例中,php脚本不包含任何html标记,只包含php代码。字体颜色表示您忘记了引号。
xmlhttp.open(“GET”,some.php”,true);
=>xmlhttp.open(“GET”,“some.php”,true)
这在@user1722564上运行得非常好。它将$data变量转换为json对象,允许我操作它并从中检索信息。