如何使用jQuery从多个元素获取数据并通过php发送到MySQL表

时间:2021-11-23 00:14:06

I have a menu something like this:

我有一个这样的菜单:

 <ul>
  <li data-id=1 data-gameresult=2:0></li>
  <li data-id=3 data-gameresult=1:0></li>
  <li data-id=4 data-gameresult=0:0></li>
  <li data-id=5 data-gameresult=1:3></li>
 </ul>

I want to get data from each 'li' element and send it over jquery ajax function to php file to create single SQL query.

我想从每个'li'元素获取数据并通过jquery ajax函数将其发送到php文件以创建单个SQL查询。

I know how to use jquery ajax, something like:

我知道如何使用jquery ajax,如:

$.ajax({
type:"POST",
url: "file.php",
data:{'id':id,'gameresult':gameresult}
});

But I can only send one li's data with this approach.

但我只能用这种方法发送一个李的数据。

2 个解决方案

#1


1  

You're basically there, right?

你基本上就在那里,对吧?

You've declared an object called data, which has 2 properties:

您已经声明了一个名为data的对象,它有2个属性:

  • id
  • ID
  • gameresult
  • gameresult

You want to have an array of these objects, so PHP receives the whole lot in one go.

您希望拥有这些对象的数组,因此PHP可以一次性接收整个批次。

var json = {
   gameResults: []
};

$("li").each(function (i, li) {
   json.gameResults.push($(li).data('gameresult'));
});

This gives you a JSON object with everything as an array:

这为您提供了一个JSON对象,其中所有内容都是数组:

{"gameResults":["2:0","1:0","0:0","1:3"]}

Alternatively you can have an array of objects, so each ID/gamescore pair is maintained:

或者,您可以拥有一个对象数组,因此每个ID /游戏核心对都会被维护:

$("li").each(function (i, li) {
   json.gameResults.push({
       id: $(li).data('id'),
       gamescore: $(li).data('gameresult')
   });
});

...which gives:

...这使:

{"gameResults": [
   {"id":1,"gamescore":"2:0"},
   {"id":3,"gamescore":"1:0"},
   {"id":4,"gamescore":"0:0"},
   {"id":5,"gamescore":"1:3"}
]}

Then just pass json to jQuery as your data value.

然后将json作为数据值传递给jQuery。

On the PHP side, you'll receive a post object with this associative (or numerically indexed) array - which you can craft into a bulk SQL insert.

在PHP方面,您将收到一个带有此关联(或数字索引)数组的帖子对象 - 您可以将其制作成批量SQL插入。

JSFiddle demo:

JSFiddle演示:


Update: Processing on the PHP side.

To get the object to your PHP script, adjust your AJAX request like so:

要将对象提供给PHP脚本,请调整您的AJAX请求,如下所示:

 $.ajax({
     type:"POST",
     url: "file.php",
     data: json,
     success: function(data) {
         document.write("<pre>" + data);
     }
 });

(Note I've changed data: ... and added success: .... We now pass the json variable as the data property, and use a call-back to handle a successful AJAX request. I won't go into detail on this subject - but rather point you to the jQuery documentation. You should handle errors etc as well - everything you need is on that link.)

(注意我已经更改了数据:...并且增加了成功:....我们现在将json变量作为data属性传递,并使用回调来处理成功的AJAX请求。我不会详细介绍关于这个主题 - 而是指向jQuery文档。你也应该处理错误等 - 你需要的一切都在那个链接上。)

file.php will receive a POST request - which in PHP means there's an automagical global variable called $_POST which will contain some data from the AJAX request. Again, I won't repeat what's in the PHP documentation - but just remind you to validate and sanitize everything - you absolutely must not trust this data implicitly. It could be anything, from anywhere, and it could be evil (like a SQL injection).

file.php将收到一个POST请求 - 在PHP中意味着有一个名为$ _POST的自动全局变量,它将包含来自AJAX请求的一些数据。同样,我不会重复PHP文档中的内容 - 但只是提醒您验证并清理所有内容 - 您绝对不能隐含地信任这些数据。它可以是任何东西,从任何地方,它可能是邪恶的(如SQL注入)。

I've written a test file.php script:

我写了一个测试file.php脚本:

<?php
var_dump($_POST);

Making a successful AJAX request to it (using the exact JavaScript above) returns some data (which appears in the JavaScript success call-back in the data parameter):

向它发出成功的AJAX请求(使用上面的确切JavaScript)会返回一些数据(出现在data参数中的JavaScript成功回调中):

array(1) {
  ["gameResults"]=>
  array(4) {
    [0]=>
    array(2) {
      ["id"]=>
      string(1) "1"
      ["gamescore"]=>
      string(3) "2:0"
    }
    [1]=>
    array(2) {
      ["id"]=>
      string(1) "3"
      ["gamescore"]=>
      string(3) "1:0"
    }
    [2]=>
    array(2) {
      ["id"]=>
      string(1) "4"
      ["gamescore"]=>
      string(3) "0:0"
    }
    [3]=>
    array(2) {
      ["id"]=>
      string(1) "5"
      ["gamescore"]=>
      string(3) "1:3"
    }
 }

It's getting a bit inception-like now ... so I'll explain what's happened.

它现在变得有点开始了......所以我会解释发生了什么。

The browser's JavaScript engine has grabbed the data from the li elements, crafted a JSON object, submitted it (asynchronously in the background - via AJAX) to file.php, which has literally "dumped" all the data it received back to the browser.

浏览器的JavaScript引擎从li元素中获取数据,制作了一个JSON对象,并将其(在后台异步地 - 通过AJAX)提交给file.php,后者将收到的所有数据“转储”回浏览器。

The document.write(...) was just a quick hack to debug what came back from file.php - or put it another way, it just outputs the PHP var_dump(...) result to the browser screen. Behind the scenes, there's been a request made to the PHP script, some server-side processing, a response made back and then some client-side processing to finish! #winning

document.write(...)只是一个快速的黑客来调试从file.php返回的内容 - 或换句话说,它只是将PHP var_dump(...)结果输出到浏览器屏幕。在幕后,有一个对PHP脚本的请求,一些服务器端处理,一个响应回来,然后一些客户端处理完成! #winning

On the PHP side then, we can process the $_POST object (remembering to sanitize everything!) like a normal PHP array:

在PHP方面,我们可以处理$ _POST对象(记住清理所有内容!),就像普通的PHP数组一样:

foreach ($_POST['gameResults'] as $gameResult) {
    print $gameResult['id'] . ' ==> ' . $gameResult['gamescore'] . "<br>";
}

We get output like this:

我们得到这样的输出:

1 ==> 2:0
3 ==> 1:0
4 ==> 0:0
5 ==> 1:3

(We've just iterated the game results on the PHP side and formatted them as very basic HTML.)

(我们只是在PHP端迭代游戏结果,并将它们格式化为非常基本的HTML。)

I guess at this point you want to build a big bulk SQL insert? That's a bit much for me to go into in this single post - so I'll suggest you search * (or open a new question) to find out about that.

我想在这一点上你想构建一个大的SQL插件吗?这对我来说在这篇文章中有点多 - 所以我建议你搜索*(或者打开一个新问题)来了解这一点。

Happy coding!

快乐的编码!

#2


0  

You have to iterate all li element by using jquery map or each function.

您必须使用jquery map或每个函数迭代所有li元素。

var id = $('li').map(function() {
    return $(this).attr('data-id');
}).get();

var gameresult = $('li').map(function() {
    return $(this).attr('data-gameresult');
}).get();

#1


1  

You're basically there, right?

你基本上就在那里,对吧?

You've declared an object called data, which has 2 properties:

您已经声明了一个名为data的对象,它有2个属性:

  • id
  • ID
  • gameresult
  • gameresult

You want to have an array of these objects, so PHP receives the whole lot in one go.

您希望拥有这些对象的数组,因此PHP可以一次性接收整个批次。

var json = {
   gameResults: []
};

$("li").each(function (i, li) {
   json.gameResults.push($(li).data('gameresult'));
});

This gives you a JSON object with everything as an array:

这为您提供了一个JSON对象,其中所有内容都是数组:

{"gameResults":["2:0","1:0","0:0","1:3"]}

Alternatively you can have an array of objects, so each ID/gamescore pair is maintained:

或者,您可以拥有一个对象数组,因此每个ID /游戏核心对都会被维护:

$("li").each(function (i, li) {
   json.gameResults.push({
       id: $(li).data('id'),
       gamescore: $(li).data('gameresult')
   });
});

...which gives:

...这使:

{"gameResults": [
   {"id":1,"gamescore":"2:0"},
   {"id":3,"gamescore":"1:0"},
   {"id":4,"gamescore":"0:0"},
   {"id":5,"gamescore":"1:3"}
]}

Then just pass json to jQuery as your data value.

然后将json作为数据值传递给jQuery。

On the PHP side, you'll receive a post object with this associative (or numerically indexed) array - which you can craft into a bulk SQL insert.

在PHP方面,您将收到一个带有此关联(或数字索引)数组的帖子对象 - 您可以将其制作成批量SQL插入。

JSFiddle demo:

JSFiddle演示:


Update: Processing on the PHP side.

To get the object to your PHP script, adjust your AJAX request like so:

要将对象提供给PHP脚本,请调整您的AJAX请求,如下所示:

 $.ajax({
     type:"POST",
     url: "file.php",
     data: json,
     success: function(data) {
         document.write("<pre>" + data);
     }
 });

(Note I've changed data: ... and added success: .... We now pass the json variable as the data property, and use a call-back to handle a successful AJAX request. I won't go into detail on this subject - but rather point you to the jQuery documentation. You should handle errors etc as well - everything you need is on that link.)

(注意我已经更改了数据:...并且增加了成功:....我们现在将json变量作为data属性传递,并使用回调来处理成功的AJAX请求。我不会详细介绍关于这个主题 - 而是指向jQuery文档。你也应该处理错误等 - 你需要的一切都在那个链接上。)

file.php will receive a POST request - which in PHP means there's an automagical global variable called $_POST which will contain some data from the AJAX request. Again, I won't repeat what's in the PHP documentation - but just remind you to validate and sanitize everything - you absolutely must not trust this data implicitly. It could be anything, from anywhere, and it could be evil (like a SQL injection).

file.php将收到一个POST请求 - 在PHP中意味着有一个名为$ _POST的自动全局变量,它将包含来自AJAX请求的一些数据。同样,我不会重复PHP文档中的内容 - 但只是提醒您验证并清理所有内容 - 您绝对不能隐含地信任这些数据。它可以是任何东西,从任何地方,它可能是邪恶的(如SQL注入)。

I've written a test file.php script:

我写了一个测试file.php脚本:

<?php
var_dump($_POST);

Making a successful AJAX request to it (using the exact JavaScript above) returns some data (which appears in the JavaScript success call-back in the data parameter):

向它发出成功的AJAX请求(使用上面的确切JavaScript)会返回一些数据(出现在data参数中的JavaScript成功回调中):

array(1) {
  ["gameResults"]=>
  array(4) {
    [0]=>
    array(2) {
      ["id"]=>
      string(1) "1"
      ["gamescore"]=>
      string(3) "2:0"
    }
    [1]=>
    array(2) {
      ["id"]=>
      string(1) "3"
      ["gamescore"]=>
      string(3) "1:0"
    }
    [2]=>
    array(2) {
      ["id"]=>
      string(1) "4"
      ["gamescore"]=>
      string(3) "0:0"
    }
    [3]=>
    array(2) {
      ["id"]=>
      string(1) "5"
      ["gamescore"]=>
      string(3) "1:3"
    }
 }

It's getting a bit inception-like now ... so I'll explain what's happened.

它现在变得有点开始了......所以我会解释发生了什么。

The browser's JavaScript engine has grabbed the data from the li elements, crafted a JSON object, submitted it (asynchronously in the background - via AJAX) to file.php, which has literally "dumped" all the data it received back to the browser.

浏览器的JavaScript引擎从li元素中获取数据,制作了一个JSON对象,并将其(在后台异步地 - 通过AJAX)提交给file.php,后者将收到的所有数据“转储”回浏览器。

The document.write(...) was just a quick hack to debug what came back from file.php - or put it another way, it just outputs the PHP var_dump(...) result to the browser screen. Behind the scenes, there's been a request made to the PHP script, some server-side processing, a response made back and then some client-side processing to finish! #winning

document.write(...)只是一个快速的黑客来调试从file.php返回的内容 - 或换句话说,它只是将PHP var_dump(...)结果输出到浏览器屏幕。在幕后,有一个对PHP脚本的请求,一些服务器端处理,一个响应回来,然后一些客户端处理完成! #winning

On the PHP side then, we can process the $_POST object (remembering to sanitize everything!) like a normal PHP array:

在PHP方面,我们可以处理$ _POST对象(记住清理所有内容!),就像普通的PHP数组一样:

foreach ($_POST['gameResults'] as $gameResult) {
    print $gameResult['id'] . ' ==> ' . $gameResult['gamescore'] . "<br>";
}

We get output like this:

我们得到这样的输出:

1 ==> 2:0
3 ==> 1:0
4 ==> 0:0
5 ==> 1:3

(We've just iterated the game results on the PHP side and formatted them as very basic HTML.)

(我们只是在PHP端迭代游戏结果,并将它们格式化为非常基本的HTML。)

I guess at this point you want to build a big bulk SQL insert? That's a bit much for me to go into in this single post - so I'll suggest you search * (or open a new question) to find out about that.

我想在这一点上你想构建一个大的SQL插件吗?这对我来说在这篇文章中有点多 - 所以我建议你搜索*(或者打开一个新问题)来了解这一点。

Happy coding!

快乐的编码!

#2


0  

You have to iterate all li element by using jquery map or each function.

您必须使用jquery map或每个函数迭代所有li元素。

var id = $('li').map(function() {
    return $(this).attr('data-id');
}).get();

var gameresult = $('li').map(function() {
    return $(this).attr('data-gameresult');
}).get();