duanrong5927 2010-10-22 18:38
浏览 42
已采纳

JQuery + Json - 一个例子的第一步

I need (recently) to get an array from the server after an ajax call created by jquery. I know that i can do it using JSON. But i don't know how to implement it with JQuery (im new with JSON). I try to search in internet some example, but i didnt find it.

This is the code :

// js-jquery function
function changeSponsor() {
    $.ajax({
        type: 'POST',
        cache: false,
        url: './auth/ajax.php',
        data: 'id=changespon',
        success: function(msg) {
            // here i need to manage the JSON object i think
        }
    });
    return false;
}

// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
    $linkspon[0]="my ";
    $linkspon[1]="name ";
    $linkspon[2]="is ";
    $linkspon[3]="marco!";

    echo $linkspon;
}

in fact, i need to get the array $linkspon after the ajax call and manage it. How can do it? I hope this question is clear. Thanks

EDIT

ok. this is now my jquery function. I add the $.getJSON function, but i think in a wrong place :)

function changeSponsor() {
    $.ajax({
        type: 'POST',
        cache: false,
        url: './auth/ajax.php',
        data: 'id=changespon',
        dataType: 'json',
        success: function(data) {
            $.getJSON(url, function(data) { alert(data[0]) } ); 
        }       
    });

    return false;
}
  • 写回答

2条回答 默认 最新

  • drny20290570 2010-10-22 18:54
    关注

    Two things you need to do.

    1. You need to convert your array to JSON before outputting it in PHP. This can easily be done using json_encode, assuming you have a recent version of PHP (5.2+). It also is best practice for JSON to use named key/value pairs, rather than a numeric index.
    2. In your jQuery .ajax call, set dataType to 'json' so it know what type of data to expect.

      // JS/jQuery
      function changeSponsor() {
          $.ajax({
              type: 'POST',
              cache: false,
              url: './auth/ajax.php',
              data: 'id=changespon',
              dataType: 'json',
              success: function(data) {
                  console.log(data.key); // Outputs "value"
                  console.log(data.key2); // Outputs "value2"
              }
          });
          return false;
      }
      
      
      // PHP
      if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
          $linkspon["key"]= "value";
          $linkspon["key2"]= "value2";
          echo json_encode($linkspon);
      }
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题