doushao8421 2012-04-20 21:37
浏览 41
已采纳

将php或xmlhttp.responseText中的列表传递给javascript

I have a list in javascript that is to be changed by the content of a database when the user clicks a link or slides a bar. I currently use a xmlhttp request to fetch a php page which generates the list. I have a static list working in this form:

var mark_list = [
{ "EntID" : 3, "x" : 100, "y" : 400},
];

I tried to have the php page generate the { "EntID" : 3, "x" : 100, "y" : 400} and set mark_list equal to responseText but I believe that's just a string. I'm struggling to find a way to get this new list into the variablie.

Does anyone have any suggestions or solutions? Your help would be greatly appreciated.

Kallum

  • 写回答

2条回答 默认 最新

  • dqq48152418 2012-04-20 21:43
    关注

    Make sure the browser has a JSON object by including the json script from here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

    It will defer to the native browser JSON object if available, and if not, will add it so that this functionality is available in browsers that don't currently support it.

    Then in your code, after you receive the output from the PHP script, run this:

    var mark_list = JSON.parse(responseText);
    

    Based on the output from the PHP script, you may need to do this:

    var stuff = JSON.parse(responseText);
    var mark_list = [stuff];
    

    This will convert the JSON string the PHP returns into an actual javascript object.

    In your PHP code you can do something like this:

    $output = array(
        array(
            'EntId' => 3,
            'x' => 100,
            'y' => 400,
        ),
    );
    
    echo json_encode($output);
    

    Then you can use the var mark_list = JSON.parse(responseText); option in your JavaScript.

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

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测