简体   繁体   English

将json_encoded数组传递给jQuery

[英]Passing json_encoded array to jQuery

I am trying to pass an array I am creating in PHP using json_encode() . 我试图传递使用json_encode()在PHP中创建的数组。 I am running an AJAX request, see as follows: 我正在运行一个AJAX请求,如下所示:

AJAX CALL: AJAX通话:

$.ajax({
        type: "POST",
        url: "../includes/ajax.php?imagemeta=1",
        data: {
            'id' : $(this).attr('id')
        },
        datatype:"json",
        success: function(data) {
            console.log(data);
            console.log(data["image_height"]);
        },
        error: function(data) {
            console.log(data);
        }
    });

PHP JSON RESPONSE: PHP JSON响应:

if(isset($_GET["imagemeta"])){

$id = intval($_POST["id"]);
$path = "../uploads/images/" . $fm->selectImageById($id);
$meta = array();

list($width, $height) = getimagesize($path);
$meta["image_height"]   = $height . 'px';
$meta["image_width"]    = $width . 'px';

print json_encode($meta);

} }

Although, the console.log(data) returns the following: {"image_height":"1374px","image_width":"920px"} 虽然,console.log(data)返回以下内容: {"image_height":"1374px","image_width":"920px"}

The following line console.log(data["image_height"]) returns undefined. 下面的console.log(data [“ image_height”])返回未定义。

I have tried multiple attempts and have read through majority of the top rated questions regarding the subject. 我尝试了多次尝试,并阅读了有关该主题的大多数最高评分的问题。 I am fairly new with JSON encoding so please inform me if I have a misunderstanding somewhere. 我刚开始使用JSON编码,所以如果我在某个地方有误会,请通知我。

datatype:"json",

should be: 应该:

dataType:"json",
    ^

Javascript is case-sensitive. Javascript区分大小写。

If console.log displaying you following:- 如果console.log显示以下内容:

{"image_height":"1374px","image_width":"920px"}

Then you can access "image_height" as follows:- 然后您可以按以下方式访问“ image_height”:

data.image_height;

Either set php JSON response header or return plain text from php and use $.parseJSON in success function. 设置php JSON响应标头或从php返回纯文本,然后在成功函数中使用$ .parseJSON。

 success: function(data) {
        jSon = $.parseJSON(data);
        console.log(jSon.image_height);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM