简体   繁体   English

在php中使用json_encode如何在javascript中使用

[英]using json_encode in php how to consume in javascript

I am returning data from php by json_encode while($row = mysql_fetch_assoc($results)){ echo json_encode($row); 我正在通过json_encode从php返回数据, while($row = mysql_fetch_assoc($results)){ echo json_encode($row); } }

now when i console log i get {"username":"foster","sport":"tennis","latitude":"19.166901","longitude":"72.951720"}{"username":"anirudh","sport":"rugby","latitude":"19.218330","longitude":"72.978088"} 现在,当我通过控制台登录时,我得到{“ username”:“ foster”,“ sport”:“ tennis”,“ latitude”:“ 19.166901”,“ longitude”:“ 72.951720”} {“ username”:“ anirudh”,“运动”:“橄榄球”,“纬度”:“ 19.218330”,“经度”:“ 72.978088”}

question is how do i gain access to the returned fields. 问题是我如何获得对返回字段的访问权限。 its being returned as a string. 它以字符串形式返回。 When i do JSON.parse i get an error 当我执行JSON.parse时出现错误

VM1115:1 Uncaught SyntaxError: Unexpected token { in JSON at position 85
    at JSON.parse (<anonymous>)
    at Object.success (form.js:43)
    at j (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at x (jquery.min.js:4)
    at XMLHttpRequest.b (jquery.min.js:4)

Please advice. 请指教。

Many Thanks Archit Wahi 非常感谢Archit Wahi

您不需要解析json数据。只需使用data.objectname即可获取

The way you are creating your json you will have difficulties parsing it in js. 创建json的方式很难在js中解析。 This is the way you should go about it. 这就是您应该采取的方式。

$result = array();
while($row = mysql_fetch_assoc($results))
{
    $result[] = $row;
}
echo json_encode($result);

Which will give you a json which you can parse if required using: 这将为您提供一个json,您可以根据需要使用以下方法进行解析:

var result = JSON.parse(thePHPresult);

and your JSON will look something like: 并且您的JSON将类似于:

[{"field_1":1,"field_2":"test1"},{"field_1":2,"field_2":"test2"},{"field_1":3,"field_2":"test3"}]

Which is a JSON array and can be accesed as: 这是一个JSON数组,可以添加为:

 var theJSON = [{"field_1":1,"field_2":"test1"},{"field_1":2,"field_2":"test2"},{"field_1":3,"field_2":"test3"}]; for(var i=0; i< theJSON.length; i++) { console.log(theJSON[i].field_2); } 

You have to add the rows to an array and after the while, you can echo the result of json_encode(). 您必须将行添加到数组中,片刻之后,您可以回显json_encode()的结果。 Simple rows echoed after each are not valid JSON. 在每行之后回显的简单行不是有效的JSON。

Do you get the error when you just have one result from the database or is it when you have multiple rows? 当您仅从数据库中获得一个结果时,还是在多行时得到错误?

If you store all your rows in an array and then echo json encode the array, will that solve your issue? 如果将所有行存储在一个数组中,然后对数组进行echo json编码,那将解决您的问题吗?

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

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