简体   繁体   中英

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); }

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"}

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

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

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

The way you are creating your json you will have difficulties parsing it in 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:

var result = JSON.parse(thePHPresult);

and your JSON will look something like:

[{"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:

 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(). Simple rows echoed after each are not valid 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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