weixin_33713707 2018-04-28 17:41 采纳率: 0%
浏览 86

使用ajax将信息传递给数据库

I am trying to pass the information from my HTML list to a database via Ajax jQuery. I'm unsure if my approach will work and how I should proceed. My biggest issue is how to get the correct information from the list so I can pass them to the PHP page and insert them. What I'm getting from my get_data function is something like this:

James blue Looks Good

Rebecka black Looks very bad

What I will be trying to do is insert this info to my database in the colors.php file. My table looks like this:

person
color_name
opinion

So it should for example look like this:

person = James
color_name = blue
opinion = Looks good

HTML

<div>
  <ul data-person="James">
    <li data-color_opinion="blue">Looks good</li>
    <li data-color_opinion="green">Looks ok</li>
  </ul>
  <ul data-person="Rebecka">
    <li data-color_opinion="blue">Looks bad</li>
    <li data-color_opinion="black">Looks very bad</li>
  </ul>
</div>

JQuery Ajax

function get_data() {
  $.each($('ul'), function(i, el) {
    $.each($(el).find("[data-color_opinion]"), function(j, child) {
      let person = $(el).data('person');
      let color_name = $(child).data('color_opinion');
      let opinion = $(child).text();
    });
  });
};

$.ajax({
  type: "POST",
  dataType: "json",
  url: 'colors.php',
  data: get_data(),
  success: function(data) {
    //data is what your PHP page send you back,
    //what do you want to do with it?
    console.log(data);
  }
});
  • 写回答

3条回答 默认 最新

  • weixin_33691817 2018-04-28 17:49
    关注

    Each iteration is overwriting the values of the person, color_name, and opinion variables. And the get_data() is not returning anything anyway, so nothing gets assigned to data and nothing gets posted to your PHP page.

    You need to save the collected values in each iteration, probably in an array, and then return that array at the end. I don't know what your PHP page is expecting, but something like this:

    function get_data() {
      var data = [];
      $.each($('ul'), function(i, el) {
        $.each($(el).find("[data-color_opinion]"), function(j, child) {
          let person = $(el).data('person');
          let color_name = $(child).data('color_opinion');
          let opinion = $(child).text();
          data.push({ Person: person, ColorName: color_name, Opinion: opinion });
        });
      });
      return data;
    };

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python