使用AJAX发布Jquery,序列化如何工作?

时间:2017-04-08 06:26:41

标签: javascript jquery ajax

我需要创建一个带有JQuery的AJAX请求,一旦它被验证为不是空的,就会中断一个表单并将该表单提交到一个url,然后它需要获取这些表单值并将它们放入一些变量中,这样我就能用它们来做事。问题是我不知道AJAX如何工作和

我不知道序列化是如何工作的,而且它的文档似乎相当抽象。我也无法阻止网页切换网址

newGame.onsubmit = function(e) {
  var inputs = form.getElementsByTagName('input');
  for (var i = 0; i < inputs.length; i++) {
    // only validate the inputs that have the required attribute
    if (inputs[i].hasAttribute("required")) {
      if (inputs[i].value == "") {
        // found an empty field that is required
        alert("Enter Player Name!");

      }
    }
  }

  $.ajax({
      url: 'http://ins.mtroyal.ca/~nkhemka/process.php',
      type: 'post',
      dataType: 'json',
      data: $('#newGame').serialize(), // i have no idea how this works
      success: function loadName() //this would contain the code to get the player names loaded into variables

    }
    e.preventDefault(); // I dont know where this should go to keep the page from going to the URL
  );

}
<div class="nGame">
  <form id="newGame" action="http://ins.mtroyal.ca/~nkhemka/process.php" method="post" name="newGame">
    Player 1 Name:
    <input type="text" name="player1" required>
    <br> Player 2 Name:
    <input type="text" name="player2" required>
    <br>
    <input type="submit" value="New Game">
  </form>
</div>

3 个答案:

答案 0 :(得分:0)

Jquery ajax和表单序列化的工作方式如下:

$.ajax(
{
    url: 'http://ins.mtroyal.ca/~nkhemka/process.php',
    type: 'post',
    data: 
    {
        frmData : $('#newGame').serialize();  // It will send value like index1=value1&index2=value2
    },
    success: function(response)
    {
        // Check the response value and show alert
    }
});

process.php

$frmData = $_POST['frmData'];
$params = array();
parse_str($frmData, $params);

print_r($params);

它将提供0,1,2的所有表单值。索引如:

array(
    'index1' => 'value1',
    'index2' => 'value2'
    // and so on
);

答案 1 :(得分:0)

编辑1:

1)在提交输入id="submit"

中添加了新的id属性

2)点击提交ID运行该功能并停止默认表单子项g e.preventDefault();

$(document).ready(function() {
  $('#submit').click(function(e) {
    e.preventDefault();
    err = 0;
    $('input').each(function() {
      if ($(this).prop('required') && $(this).val() == '') {
        err = 1;
        alert("Enter " + $(this).attr('name') + " Name");
      }
    });
    if (err == 1) {
      return false;
    }
    $.ajax({
      url: 'http://ins.mtroyal.ca/~nkhemka/process.php',
      type: 'post',
      dataType: 'json',
      data: $('#newGame').serialize(),
      success: function() {
        // loadName(); 
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nGame">
  <form id="newGame" action="http://ins.mtroyal.ca/~nkhemka/process.php" method="post" name="newGame">
    Player 1 Name:
    <input type="text" name="player1" required>
    <br> Player 2 Name:
    <input type="text" name="player2" required>
    <br>
    <input type="submit" id="submit" value="New Game">
  </form>
</div>

1)e.preventDefault();它会阻止默认表单提交操作

2)如果任何字段为空,则应使用return false;停止调用ajax。

if(err==1)
  {
     return false;

     // any of fied is empty you should retun false to stop calling ajax request

  }

3).serialize()方法以标准URL编码表示法创建文本字符串。它可以作用于已选择单个表单控件的jQuery对象,例如<input><textarea><select>:$(“input,textarea,select”)。serialIile();

4)如果你需要在ajax上调用另一个函数,它应该是这样的

success: function()
      {

         loadName() //this would contain the code to get the player names loaded into variables

       }

Ajax:

newGame.onsubmit = function(e) {
    e.preventDefault(); // it prevent the default form submition action 
    var inputs = form.getElementsByTagName('input');
    err = 0;
    for (var i = 0; i < inputs.length; i++) {
      if (inputs[i].hasAttribute("required")) {
        if (inputs[i].value == "") {
          err = 1;
          alert("Enter Player Name!");
        }
      }
    }
    if (err == 1) {
      return false;
      // any of fied is empty you should retun false to stop calling ajax request
    }
    $.ajax({
        url: 'http://ins.mtroyal.ca/~nkhemka/process.php',
        type: 'post',
        dataType: 'json',
        data: $('#newGame').serialize(),
        // .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls, such as <input>, <textarea>, and <select>: $( "input, textarea, select" ).serialize();
        success: function(res) {
          loadName() //this would contain the code to get the player names loaded into variables
        }
      );
    }

答案 2 :(得分:-1)

假设您要发布包含某个字段的表单,将其包装为

var formNewGame = { "name":"John", "age":30, "city":"New York"};

在你的ajax电话中,改变

data: $('#newGame').serialize()

进入

data: JSON.stringify(formNewGame );