id没有正确传递给ajax调用

时间:2017-12-29 14:25:40

标签: javascript jquery ajax

我的页面上有两个编辑按钮。请参阅下面的最小可行示例:

<!DOCTYPE html>
<html>

<head>
  <title>Jquery Modal</title>
</head>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<script>
  $(document).ready(function() {

    //get base URL *********************
    var url = $('#url').val();

    //display modal form for creating new product *********************
    $('.btn_add').click(function() {
      $('#btn-save').val("add");
      $('#myModal').modal('show');
    });

    //display modal form for product EDIT ***************************
    $(document).on('click', '.open_modal', function() {
      var product_id = $(this).val();
      // Populate Data in Edit Modal Form
      $.ajax({
        type: "GET",
        url: url + '/edit/' + product_id,
        success: function(data) {
          console.log(data);
          $('#product_id').val(data.id);
          $('#name').val(data.name);
          $('#btn-save').val("update");
          $('#myModal').modal('show');
        },
        error: function(data) {
          console.log('Error:', data);
        }
      });
    });

    //create new product / update existing product ***************************
    $("#btn-save").click(function(e) {
      $.ajaxSetup({
        headers: {
          'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
        }
      })

      e.preventDefault();
      var formData = {
        name: $('#name').val(),
        //price: $('#price').val(),
      }
      console.log("formData: " + formData);

      //used to determine the http verb to use [add=POST], [update=PUT]
      var state = $('#btn-save').val();
      var type = "PUT"; //for creating new resource
      var product_id = $('#product_id').val();;
      var my_url = url + '/edit/' + product_id;
      console.log("state: " + state)
      console.log("product_id: " + product_id)
      console.log("my_url: " + my_url)
      console.log("formData: " + formData);
      $.ajax({
        type: type,
        url: my_url,
        data: formData,
        dataType: 'json',
        success: function(data) {
          console.log("data: " + data);
          $('#frmProducts').trigger("reset");
          $('#myModal').modal('hide')
        },
        error: function(data) {
          console.log('Error:', data);
        }
      });
    });
  });
</script>

<body>
  <div>
    <h1>My First Heading</h1>
    <tr>
      <a id="product9988" name="btn_add" class="btn_add" data-target="#myModal"><sup> EDIT - Sector</sup></a>
      </br>
      <a id="product9988" name="btn_add" class="btn_add" data-target="#myModal"><sup> EDIT - Country of Origin</sup></a>
    </tr>
  </div>

  <!-- MODAL SECTION -->
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
          <h4 class="modal-title" id="myModalLabel">Edit</h4>
        </div>
        <div class="modal-body">
          <form id="frmProducts" name="frmProducts" class="form-horizontal" novalidate="">
            <div class="form-group error">
              <label for="inputName" class="col-sm-3 control-label">Name: </label>
              <div class="col-sm-9">
                <input type="text" class="form-control has-error" id="name" name="name" placeholder="Country of Origin" value="">
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-primary" id="btn-save" value="update">Edit Entry</button>
          <input type="hidden" id="product_id" name="product_id" value="101">
        </div>
      </div>
    </div>
  </div>

</body>

</html>

正如您所看到的,将错误的product_id传递给ajax请求。这两个属性都有product_id = 9988,而不是传递的product_id product_id = 101。该值不会被ajax请求覆盖。

下面你可以看到我的控制台的输出:

enter image description here

有任何建议如何解决这个问题?

0 个答案:

没有答案