来自php的jQuery Ajax响应变量

时间:2022-10-09 00:28:06

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?

我有一个简单的问题,但未能找到我需要的确切解决方案。如何使用jQuery $ .ajax调用只回显两个PHP变量的PHP文件,并将它们保存到响应中的javascript变量中?

1 个解决方案

#1


6  

you would do something like:

你会做类似的事情:

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

and then in ajax_responder.php

然后在ajax_responder.php中

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

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

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

#1


6  

you would do something like:

你会做类似的事情:

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

and then in ajax_responder.php

然后在ajax_responder.php中

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

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

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