解析使用jQuery的Ajax对象的PHP数组 [英] Parse PHP array of objects with jQuery Ajax

查看:196
本文介绍了解析使用jQuery的Ajax对象的PHP数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让对象与数据的数组从我的数据库到jQuery来呈现在网站上。

I'm trying to get an array of objects with data from my database into jquery to render on a website.

例如: 使用example.php

ex: example.php

<?php
function testFunction() {

$data = array()
$mydata = new stdClass;
$mydata->example = 'test';
$data[] = $mydata
return json_encode($data);
}

echo testFunction();
?>

前 index.html的

ex index.html

<script>
$.ajax({
                    type: 'POST',
                    url: 'example.php',
                    data: {map: map},   
                    cache: false,
                    dataType: 'json',                 
                    success: function(response) {
                      console.log(response[0].example);
                    }
});

</script>

输出:

执行console.log(响应);

console.log(response);

[测试,$家族:函数,$构造:函数,每个:函数,克隆:功能,清洁:函数...]

["test", $family: function, $constructor: function, each: function, clone: function, clean: function…]

的console.log(响应[0] .EXAMPLE);

console.log(response[0].example);

未定义

所以基本上,我收到的响应很好,当我登录它它给了我一个结构,它是有道理的。不过,我似乎无法找到访问数组里面我的对象的正确方式,比如我上面只返回undefined。什么是正确的语法为这个吗?

So essentially, I receive the response fine, when I log it it gives me a structure that makes sense. however I can't seem to find the correct way of accessing my objects inside the array, the example I have above only returns undefined. What is the correct syntax for this please?

推荐答案

您需要 JSON.parse(响应); 的响应。你应该能像你需要再访问它。

You need to JSON.parse(response); the response. You should be able to access it like you need then..

var parsed_reply = JSON.parse(response);

修改后居然在看code:

PHP

<?php

$data['example'] = "test";

echo json_encode($data);

?>

JAVASCRIPT

JAVASCRIPT

<script>
$.ajax({
                type: 'POST',
                url: 'example.php',
                data: {map: map},   
                cache: false,
                dataType: 'json',                 
                success: function(response) {
                  console.log(response['example']);
                }
});

</script>

OUTPUT:测试

OUTPUT: "test"

这篇关于解析使用jQuery的Ajax对象的PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆