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

mar*_*zzz 1 php arrays jquery json

我需要(最近)在jquery创建的ajax调用之后从服务器获取一个数组.我知道我可以使用JSON来做到这一点.但我不知道如何使用JQuery实现它(我刚接触JSON).我尝试在互联网上搜索一些例子,但我没有找到它.

这是代码:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

事实上,我需要在ajax调用之后获取数组$ linkspon并进行管理.怎么办?我希望这个问题很清楚.谢谢

编辑

好.这是我的jquery函数.我添加$ .getJSON函数,但我认为在错误的地方:)

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;
}
Run Code Online (Sandbox Code Playgroud)

小智 5

你需要做的两件事.

  1. 在PHP中输出数组之前,需要将数组转换为JSON.这可以使用json_encode轻松完成,假设您有最新版本的PHP(5.2+).JSON使用命名键/值对而不是数字索引也是最佳做法.
  2. 在你的jQuery .ajax调用中,将dataType设置为'json',以便它知道期望的数据类型.

    // 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);
    }
    
    Run Code Online (Sandbox Code Playgroud)