简体   繁体   English

如何使用JSON在jQuery和PHP文件之间传递多个变量?

[英]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? 如何使用带有json的jquery在PHP文件之间传递多个变量? 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. 但是,我不仅要使用.html函数,还想从PHP文件中检索多个变量,然后将其用于页面上的.html 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? 我不能只使用data因为它只能输出PHP返回的任何内容,因此,据我所知,php只能以echo()的形式返回一件事,但是我如何才能使它检索的不仅仅是一个变量? 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. 我认为我必须使用JSON,但我以前从未使用过JSON,因此如果有人可以帮助我,我将不胜感激。 Thanks. 谢谢。

You can return a JSON object from php ( Returning JSON from PHP to JavaScript? ). 您可以从php返回一个JSON对象(从PHP 返回JSON到JavaScript? )。 And then in your jquery you can acees it like this, 然后在您的jquery中,您可以像这样点它,

$.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 . 见jQuery的岗位()文档在这里 Check out the dataType parameter, which tells jQuery what kind of data to expect back from the server. 签出dataType参数,该参数告诉jQuery期望从服务器返回什么样的数据。

See the json_encode() and json_decode() PHP functions here . 此处查看json_encode()和json_decode()PHP函数。 Use json_encode() to prepare your populated data structure for echo()'ing back to the client. 使用json_encode()准备填充的数据结构,以将echo()返回到客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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