【问题标题】:using a PHP print_r array result in javascript/jquery在 javascript/jquery 中使用 PHP print_r 数组
【发布时间】:2011-02-01 13:12:39
【问题描述】:

我有一个简单的 jquery/ajax 请求到服务器,它返回数组的结构和数据。我想知道是否有一种快速的方法可以使用 jquery 来使用这个数组结构和数据;

一个简单的请求;

var token = $("#token").val();
$.ajax({ 
    type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000,
    success: function(html){ 
        // do something here with the html var 
    }                           
}); 

结果(来自 PHP 的 print_r(); 的实际结果);

    Array
    (

        [0] => Array
            (
                [username] => Emmalene
                [contents] => 
                              <ul><li class="name">ACTwebDesigns</li><li class="speech">helllllllo</li></ul>
                              <ul><li class="name">ACTwebDesigns</li><li class="speech">sds</li></ul>
                              <ul><li class="name">ACTwebDesigns</li><li class="speech">Sponge</li><li class="speech">dick</li></ul>
                              <ul><li class="name">ACTwebDesigns</li><li class="speech">arghh</li></ul>
            )

    )

我的思路是这样的

var demo = Array(html); // and then do something with the demo var

不知道这是否可行,我突然想到了。

非常感谢任何帮助。

【问题讨论】:

    标签: php jquery arrays


    【解决方案1】:

    使用JSON。 JSON 是一种轻量级的数据交换格式,可以轻松地在不同编程语言之间传输数据。

    在 PHP 中使用 json_encode 对数据进行编码:

    echo json_encode($array);
    

    在jQuery中,定义结果为JSON格式,jQuery会自动解析为:

    $.ajax({ 
        type: 'POST',
        url: './', data: 'token=' + token + '&re=8',
        cache: false,
        timeout: 5000,
        dataType: 'json',
        success: function(obj) { 
            // obj is now the same array as JS object:
            $.each(obj, function(index, row) {
                alert(row.username);
            });            
        }                           
    }); 
    

    【讨论】:

    • 对不起,我只能为答案投票,但谢谢大家。另一件事(我真的很糟糕 javascript)我如何遍历结果?
    • @Phil Jackson,我修改了我的答案,加入了一个使用 jQuery 的 each() 方法循环遍历结果的示例。
    • @Phil Jackson,您也可以尝试for() 循环,即使在 SO 上也有很多关于该主题的报道,因此我不会对此进行更深入的介绍。如果您有问题,请发布一个新问题! :)
    【解决方案2】:

    使用json_encode()。它将数组转换为可在 Javascript 中直接使用的 JSON 数据。

    【讨论】:

      【解决方案3】:

      您可以在 PHP 脚本中使用 json_encode。这将返回一个 JSON 编码的数据,您可以直接在 javascript 中使用:

      $.ajax({ 
          type: 'POST', 
          url: './', 
          data: { token: token, re: '8' }, 
          cache: false, 
          timeout: 5000,
          success: function(data){ 
              // data will already be a javascript object that you can manipulate
          }                           
      }); 
      

      【讨论】:

      • data 不会是 javascript 对象,除非您指定 dataType: 'json'
      • 如果服务器发送正确的内容类型:Content-Type: application/json
      • 我没有写内容类型,也没有将类型更改为 'json' 但仍然正确返回 alert(JSON_array[0].username);返回艾玛琳
      猜你喜欢
      • 2013-06-20
      • 1970-01-01
      • 2012-12-10
      • 1970-01-01
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多