将 PHP/MySQL 请求转换为 jQuery AJAX 请求


Converting PHP/MySQL Request into jQuery AJAX Request

我在这里踢自己的屁股,因为我一辈子都想不通......这应该是一个快速而肮脏的项目,但是,我决定尝试一些新的东西,而且我对jQuery中的AJAX方法几乎没有经验......我花了 5 天时间试图学习和理解如何正确实现 AJAX 调用,但要知道有用......我学到了一些基本的东西,但没有学到执行下面代码所需的内容。

同样,我想知道如何使用 jQuery 将此标准请求转换为 AJAX......

这是我的表单和PHP

.HTML:

<form action="categories.php?action=newCategory" method="post">
  <input name="category" type="text" />
  <input name="submit" type="submit" value="Add Categories"/>
</form>

.PHP:

<?php
if (isset($_POST['submit'])) {
  if (!empty($_POST['category'])) {
    if ($_GET['action'] == 'newCategory') {
      $categories = $_POST['category'];
      $query = "SELECT * FROM categories WHERE category ='$categories' ";
      $result = mysql_query($query) or die(mysql_error());
      if (mysql_num_rows($result)) {
        echo '<script>alert("The Following Catergories Already Exist: ' . $categories . '")</script>';
      } else {
    // Simply cleans any spaces
        $clean = str_replace(' ', '', $categories);
    // Makes it possible to add multiple categories delimited by a comma
        $array = explode(",", $clean);
        foreach ($array as &$newCategory) {
          mysql_query("INSERT INTO categories (category) VALUES ('$newCategory')");
        }
        echo "<script>alert('The following Categories have been added successfully: " . $categories . "')</script>";
      }
    }
  } else {
    echo "<script>alert('Please Enter at Least One Category.')</script>";
  }
}
?>

这是在后台进行调用并且不提交表单但仍发送/检索结果的正确语法。

$(function(){
  $('form').submit(function(e){
    e.preventDefault(); // stop default form submission
    $.ajax({
      url: 'categories.php',
      data: 'action=newCategory',
      success: function(data){
        //here we have the results returned from the PHP file as 'data'
        //you can update your form, append the object, do whatever you want with it
        //example:
        alert(data);
      }
    });
  });
});

也:

我不会这样做 ->

echo "<script>alert('Please Enter at Least One Category.')</script>";

就做echo 'Please Enter at Least One Category.';

如果需要创建错误系统,可以执行以下操作:

echo "Error 1001: <!> Please enter at least One Category!';

然后在 Ajax 对"成功"的回调中,我们可以将返回的对象拆分为 <!> 。要遵循的示例:

success: function(data){
  if($(data+':contains("<!>")'){
    var errMsg = $(data).split('<!>');
    alert(errMsg[0]+' : '+errMsg[1]);
    //above would output - Error 1001 : Please enter at least One Category!;
  }
}