从PHP jQuery的Ajax响应变量

问题描述:

我有一个简单的问题,但一直没能找到我所需要的精确解。我如何使用jQuery的$就调用一个PHP文件,只是回声两个PHP变量,并将其保存到JavaScript变量的反应呢?

I've got a simple question, but haven't been able to find the exact solution I need. How can I use a jQuery $.ajax to call a PHP file that just echos two PHP variables, and save them to javascript variables in the response?

你会做这样的事情:

$.getJSON('ajax_responder.php', function(data){
        window.var1 = data.var1;
        window.var2 = data.var2;
});

,然后在ajax_responder.php

and then in ajax_responder.php

<?php
    header('Content-type: application/json');

    $var1 = 'foo';
    $var2 = 'bar';
    $data = array(
        'var1' => $var1,
        'var2' => $var2
    );
    echo(json_encode($data));
?>

http://api.jquery.com/jQuery.getJSON/