简体   繁体   English

从AJAX调用中检索多个变量到jQuery

[英]Retrieve multiple variables from an AJAX call to jQuery

I have a PHP file that requests six rows from a database. 我有一个PHP文件,该文件从数据库请求六行。 I'm using an ajax call. 我正在使用ajax调用。

I want these six rows (multiple columns) to be passed through to my main file. 我希望将这六行(多列)传递到我的主文件。 I was unable to find a way to get these values to my main page except for posting them in html in the request file and posting this as a table on my main page. 除了将这些值以html形式发布到请求文件中并将其作为表格发布到我的主页上之外,我无法找到将这些值获取到我的主页上的方法。

I don't want them on the page in a plain table for everyone to be seen. 我不希望它们在普通表的页面上显示给所有人。

So not like this: 所以不是这样的:

success: function(html) {
    $("#display").html(html).show();
}

I always need six rows at the moment but could be more later on. 我现在总是需要六行,但以后可能会更多。

One of the ideas that I had was posting it as one long string and loading this into a variable, and then reading using explode or something a-like. 我的想法之一是将其发布为一个长字符串并将其加载到变量中,然后使用explode或类似的东西进行读取。 Not sure if this is a good way to do this... 不知道这是否是一个好方法...

I am basically asking for ideas to expand my horizon. 我基本上是在寻求构想以扩大视野。

I am still learning JavaScript and jQuery so I'd rather have a good explanation than a block of working code. 我仍在学习JavaScript和jQuery,因此我希望有一个很好的解释,而不是一堆可用的代码。

Thanks in advance! 提前致谢!

PHP Side PHP方面

This is a very simple process, which you may kick yourself after grasping ;) But once you do, it opens a world of possibilities and your mind will go crazy with ideas. 这是一个非常简单的过程,您可能在掌握之后会踢自己;)但是,一旦这样做,它就会打开一个无限的可能性,您的思想将变得疯狂。

The first stage is you want to adjust your data that you will be returning to the ajax call. 第一步是您要调整将要返回到ajax调用的数据。 If you have a few rows of a few fields, you would do have something along these lines (could come from db, or assignments, whatever): 如果您的行中有几行,那么您将在以下几行中有所作为(可能来自db或赋值,无论如何):

$rows = [];
$rows[] = array('thing'=>'value 1','something'=>'blah','tertiary'=>'yup');
$rows[] = array('thing'=>'value 2','something'=>'yadda','tertiary'=>'no');
$rows[] = array('thing'=>'value 3','something'=>'woop','tertiary'=>'maybe');

Now, to get this rows of data out to ajax, you do this one simple operation: 现在,要将这行数据发送到ajax,您可以执行以下简单操作:

echo json_encode($rows);
exit; // important to not spew ANY other html

Thats all you really need to do on the PHP side of things. 这就是您在PHP方面真正需要做的所有事情。 So what did we do? 那我们做了什么? Well, we took a multidimensional array of data (usually representing what comes from a database), and encoded it in JSON format and returned it. 好吧,我们获取了多维数据数组(通常表示来自数据库的数据),并以JSON格式对其进行了编码,然后将其返回。 The above will look like this to your browser: 上面的内容在您的浏览器中看起来像这样:

[{"thing":"value 1","something":"blah","tertiary":"yup"},
 {"thing":"value 2","something":"yadda","tertiary":"no"},
 {"thing":"value 3","something":"woop","tertiary":"maybe"}]

It will have handled all escaping, and encoding of utf8 and other special characters. 它将处理所有转义,以及utf8和其他特殊字符的编码。 The joys of json_encode() ! json_encode()的乐趣!

JAVASCRIPT Side JAVASCRIPT侧面

This side is not as difficult, but theres some things to understand. 这方面并不难,但是有一些事情需要理解。 FIrst off, lets get your jquery ajax call into shape: 首先,让您的jquery ajax调用成型:

<div id="rows"></div>
<script>
$("#your-trigger").on('click',function(e){
    e.preventDefault(); // just stops the click from doing anything else
    $.ajax({
       type: "POST",
       url: 'your_ajax.php',
       data: { varname: 'value', numrows: '6' },// your sent $_POST vars
       success: function(obj) {
           // loop on the obj return rows
           for(var i = 0; i < obj.length; i++) {
               // build a div row and append to #rows container
               var row = $('<div></div>');
                   row.append('<span class="thing">'+ obj[i].thing +'</span>'); 
                   row.append('<span class="details">'+  
                                   obj[i].something +' '+ obj[i].tertiary
                               +'</span>');
               $("#rows").append(row);
           }
       },
       dataType: 'json' // important!
    });
});
</script>

So lets explain a few key points. 因此,让我们解释一些关键点。

The most important is the dataType: 'json' . 最重要的是dataType: 'json' This tells your ajax call to EXPECT a json string to turn into an object. 这告诉您对ajax调用EXPECT一个json字符串变成一个对象。 This object becomes what you define in the success function arg (which I named obj above). 该对象将成为您在成功函数arg(我在上面将其命名为obj )中定义的obj

Now, to access each specific data variable of each row, you treat it as an object. 现在,要访问每一行的每个特定数据变量,请将其视为对象。 Array of rows, each row has vars named as you named them in PHP. 行数组,每行都有vars,就像在PHP中命名它们一样。 This is where I have the for example to loop through the array of rows. 这就是我有for通过行的阵列例子来循环。

For example obj[0].thing refers to the first row of variable thing . 例如obj[0].thing指的变量的第一行thing The use of i lets you just go through all rows automatically based on length of the object. 使用i可让您根据对象的length自动遍历所有行。 A few handy things in there. 那里有一些方便的东西。

You can build any html you wish from the returned object and values. 您可以根据返回的对象和值构建任何HTML。 I just showed how to setup a <div><span class="thing"></span><span class="details"></span></div> example row. 我刚刚展示了如何设置<div><span class="thing"></span><span class="details"></span></div>示例行。 You may want to use tables, or more complex setups and code. 您可能要使用表,或更复杂的设置和代码。


To keep the return data from your ajax call, you can store it in a local or global variable like so: 为了保留来自ajax调用的返回数据,可以将其存储在本地或全局变量中,如下所示:

<script>
var globalvar;
$....('click',function(e){
    var localvar;
    $.ajax(.... success: function(obj){
        ....
        localvar = obj;
        globalvar = obj;
        ....
    });
});
</script>

Do what Frederico says above. 照弗雷德里科所说的做。 Return json from your php and get in in jQuery using ajax call. 从您的PHP返回json并使用ajax调用进入jQuery。 Something like this: http://makitweb.com/return-json-response-ajax-using-jquery-php/ . 像这样的东西: http : //makitweb.com/return-json-response-ajax-using-jquery-php/ Just skip step #3 and do what you need with received data in step #5 if you don't need it to be printed to html. 只需跳过第3步,如果不需要将接收到的数据打印到html,则对第5步中的接收数据进行所需的处理。

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

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