本文介绍了无法将PHP产生的JSON读取到我的JavaScript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AJAX请求一个返回JSON的php文件

Im using AJAX to request a php file that returns JSON

$.ajax({ url: 'php/invoice.php',
         dataType: "json",
         data: {id: 1},
         type: 'post',
         success: function(response) {
            alert(response);
         }
});

我正在使用的php文件通过json_encode回显json:

The php file im using is echoing json via json_encode:

while($row = mysqli_fetch_assoc($result))
{
   $queryResults[] = $row;
}
echo json_encode($queryResults);

php返回的示例如下:

an example of what the php is sending back is:

我发出警报(响应)时得到的是"[object Object]"

What im getting when I alert(response) is "[object Object]"

我要提醒的是json中的名字或其他任何属性. 布伦特"

What I want is to alert the first name or any other property in the json ie. "Brent"

我尝试过Alert(response.firstname);并返回undefined.

Iv'e tried alert(response.firstname); and it returns as undefined.

iv'e还尝试从ajax请求中删除dataType:"json",并在通过var obj = $ .parseJSON(response)和alert(obj.firstname)返回时解析json.

iv'e also tried to remove the dataType: "json" from the ajax request and just parse the json when it gets returned via var obj = $.parseJSON(response) and alert(obj.firstname)

我不知道我在做什么错,我也不知道当我使用json编码时,为什么在json周围有[].我认为这是因为它从json对象返回一个数组,这可能是我的问题吗?我对此并不陌生,不胜感激,不胜感激!

I dont know what im doing wrong, I also dont know why there [ ] around the json when I use json encode. Im assume its because its returning a array from json objects which may be my problem? Im new to this and would appreciate any help or resources!

我已经进行了几个小时的研究,但仍然找不到答案.预先感谢!

Iv'e done a couple hours of research and still cant find a answer. Thanks in advance!

推荐答案

问题出在这里(如 @echeese 首次指出的那样)

The problem lies here (as @echeese first pointed out)

while($row = mysqli_fetch_assoc($result))
{
   $queryResults[] = $row;
}
echo json_encode($queryResults);

注意JSON的外观(注意[..]吗?)

Notice how the JSON looks (notice the [..] ?)

[{"id":"1","firstname":"Brent","lastname":"Doe","telephone":"888888888","zip":"11111"}]

它翻译为:

0 => {"id":"1","firstname":"Brent","lastname":"Doe","telephone":"888888888","zip":"11111"}

,您需要像这样访问它:

and you need to access it like this:

response[0].firstname

这篇关于无法将PHP产生的JSON读取到我的JavaScript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 10:22