doumu8911 2014-08-27 20:05
浏览 88
已采纳

json_encode php 5.5 vs 5.3与js玩得不好

Here is the issue:

$locArr is a huge array

Then to pull that information into js I use

var oLocations = <?= json_encode($locArr, JSON_FORCE_OBJECT) ?>;

code produced by oLocations = json_encode($locArr);

var oLocations = $.parseJSON( ,"LastDataBuild":"","Drop24Hour":"NO","Pickup24Hour":"NO","MileageUnit":"MI","AirportIndicator":"0",...

Notice the first comma, this throws

Uncaught SyntaxError: Unexpected token ,

if I wrap everything in quotes so that it evaluates to a string I get

Uncaught SyntaxError: Unexpected token : 

I've tried json_encoding in and outside of the javascript, nothings seems to work.

The hardest part about all of this is that at PHP 5.5 I can use:

json_encode($locArr, JSON_PRETTY_TEXT | JSON_FORCE_OBJECT );

and everything works okay. The console will output a nice OBJECT instead of a string, without any errors.

Has anyone else experienced this or do you have any ideas of other things I can try?

Below is the current state of my code (I have been interchangeably adding/removing a few lines of code. at a time):

Declaring the var in PHP:

    $oLocations = json_encode($locArr, JSON_FORCE_OBJECT);

JS trying to use the array:

var oLocations = JSON.parse(<?= $oLocations ; ?>);
        // while(oLocations.charAt(0) !== '"'){
        //  oLocations = oLocations.substr(1);
        // };
        // oLocations = '{' + oLocations;
        // oLocations = $.parseJSON(oLocations);
        // oLocations = JSON.parse(oLocations);
        // console.log(oLocations);
        // oLocations = $.parseJSON(oLocations);

For this example JS threw this "Uncaught SyntaxError: Unexpected token o " and this is the code its referencing:

var oLocations = $.parseJSON([{"RentalLocationID":"KBR","RentalLocationStatus":"Active","RentalLocationType":"Corporate","RentalLocationName":"KBR HOURS M-F 730-6 SAT 9-1 SUN 10-2","AddressLine1":"8555 JOHN CARPENTER FWY","AddressLine2":"","Latitude":"0","Longitude":"0","AddressCity":"DALLAS","AddressState":"TX","AddressStateName":"TEXAS","AddressZipCode":"75247","AddressCountry":"US","AddressCountryName":"UNITED STATES","PhoneNumber":"214-630-6555","AltPhoneNumber":"","FAXNumber":"","ConfirmMessage":["","","",""], ...
  • 写回答

2条回答 默认 最新

  • dongshan1811 2014-09-02 21:15
    关注

    So the problem was not inside of my PHP or JS. It was inside of Expressionengine. It was picking up the "{" and trying to interpret it using EE codes. In the end we ended up using a Pretty Print alternative function that added breaks to each line pairing of key and value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重