[英]How I can pass array value of PHP into Ajax jQuery?
I get statusText: OK value, but I cannot get PHP object or array values. 我得到statusText:确定值,但无法获得PHP对象或数组值。 https://paste.fedoraproject.org/paste/1-HWWEJKvSbCYKUkoGHytA https://paste.fedoraproject.org/paste/1-HWWEJKvSbCYKUkoGHytA
I have Fedora 30 with 2.4.39 HTTPd, PHP 7.6, MySQL: 10.3.12. 我有带有2.4.39 HTTPd,PHP 7.6,MySQL:10.3.12的Fedora 30。 I'm using latest jQuery. 我正在使用最新的jQuery。 I set it into my PHP file: 我将其设置到我的PHP文件中:
header('Content-type: application/json');
$.ajax({
url: 'get.php',
type: 'post',
})
.done(function(a) {
$("#workSpace").html(a);
alert(a)
$.each(a, function( key, value ) {
$("#workSpace").html(key + ": " + value);
});
})
.fail(function(a) {
$("#workSpace").html(a);
})
.always(function(a) {
var example = Object.keys(a)
$.each(example, function( key, value ) {
$("#workSpace").html(key + ": " + value);
});
});
});
I expected work with objects or array passed by PHP like this. 我期望这样处理通过PHP传递的对象或数组。
{id:1, name: hola, description: That's an example}
{id:2, name: hello, description: That's nice}
{id:3, name: welcome, description: That's so way}
However, I just only get statusText: OK
但是,我只得到statusText: OK
you will not have many responses from your PHP in one request made, try to collect all the data received from your db in a variable. 您将不会在一个请求中收到许多来自PHP的响应,请尝试将从数据库接收的所有数据收集到一个变量中。 Modify your php code as follows. 修改您的php代码,如下所示。
header('Content-type: application/json');
$conn = new mysqli('localhost','root','example','tasks');
$stmt = $conn->query("SELECT * FROM task")->fetch_array();
$array = array();
while ($getResults = $stmt->fetch_array())
{
$array[] = $getResults;
}
/* free result set */
mysqli_free_result($getResults);
/* close connection */
mysqli_close($conn);
echo json_encode($getResults);
Regards 问候
have you try something like this : 你有没有尝试过这样的事情:
$array = array();
while ($getResults = $stmt->fetch_array())
{
$array[] = $getResults;
}
echo json_encode($array);
and adding the content type on the $.ajax request : 并在$ .ajax请求上添加内容类型:
$.ajax({
url: 'get.php',
type: 'post',
dataType: "json"
})
.done(function (a) {
$("#workSpace").html(a);
alert(a)
$.each(a, function (key, value) {
$("#workSpace").html(key + ": " + value);
});
})
.fail(function (a) {
$("#workSpace").html(a);
})
.always(function (a) {
var example = Object.keys(a)
$.each(example, function (key, value) {
$("#workSpace").html(key + ": " + value);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.