简体   繁体   中英

How to pass multiple variables between jQuery and PHP files using JSON?

How can I pass multiple variables between PHP files using jquery with json? Ex:

$.post("example.php", {asdf:asdf, sdfg:sdfg}, function(data){

        $('section').html(data);
});

But instead of just using the .html function I want to retrieve multiple variables from the PHP file and then use them for .html on my page. I can't just use data because that only outputs whatever PHP returns so to my understanding php can only return one thing in a form of an echo() , but how can I make it retrieve more than just that one variable? I think I have to use JSON but I have never used JSON before so I would appreciate it if someone could help me out. Thanks.

You can return a JSON object from php ( Returning JSON from PHP to JavaScript? ). And then in your jquery you can acees it like this,

$.post("example.php", {asdf:asdf, sdfg:sdfg}, function(data){

 $('section1').html(data.Variable1);
 $('section2').html(data.Variable2);

});

您可以让php脚本输出javascript代码来创建变量,然后只需eval()即可。

See the jQuery post() documentation here . Check out the dataType parameter, which tells jQuery what kind of data to expect back from the server.

See the json_encode() and json_decode() PHP functions here . Use json_encode() to prepare your populated data structure for echo()'ing back to the client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM