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>
    
    评论

报告相同问题?