【问题标题】:I cannot understand how AJAX differ than normal HTTP methods in a practical way?我无法理解 AJAX 在实际中与普通 HTTP 方法有何不同?
【发布时间】:2018-05-30 09:20:46
【问题描述】:

我知道 AJAX 只重新加载网页的某些部分而不刷新整个页面,不像 HTTP 必须重新刷新。

我创建了一个 TODO 应用来尝试两种不同的方法:

这是我的 HTML 有两个按钮 submit 用于 HTTP 方法发布,click button 用于 AJAX 调用

<form id="todos" action='/addTodo' method='POST'>
  <input id="inputTodo" name='todo' />
  <input type="submit" value="Add Todo" />
  <input id="button" type="button" name="todoAjax" value="Add Todo Using AJAX" />
</form>

这是我的 AJAX 调用

$(document).ready(function() {
  $("#button").click(function(e) {
    e.preventDefault();

    let todo = {
      'todo': $('#inputTodo').val()
    };

    $.ajax({
      type: "POST",
      url: "/addTodo",
      data: todo,
      success: function(todo) {
        location.reload();
      }
    });
  });
});

这是我的 post 请求的后端处理程序

app.post('/addTodo', function(req, res) 
{
  var todo = req.body.todo;

  userModel.update({
    _id: req.user._id
  }, {
    $push: {
      todos: todo
    }
  }, function(err, done) {
    if (err)
      return err;
    return done;
  });
  res.redirect('/profile');
});

在这两种方法中,我都会刷新整个页面以查看添加的 TODO 在普通的http方法中使用res.redirect,在AJAX方法中使用location.reload(),AJAX方法不应该在不刷新页面的情况下添加TODO吗?

【问题讨论】:

  • 我不确定你到底在问什么,但来自普通方法和 AJAX 的 HTTP 请求是相同的。不同之处在于如何处理响应。在正常请求中,会返回整个 HTML 文档并将其加载到浏览器中。在 AJAX 请求中,您应该只返回您想要在现有文档中更新的内容(或者您可以用来更新当前文档的数据结构,例如 JSON 或XML)。 AJAX 请求也意味着当前页面仍然加载在浏览器中。

标签: jquery node.js ajax http crud


【解决方案1】:

除了在 Ajax 中执行 location.reload() 之外,您可以在其中添加一个 div 来放置 /profile 中的内容

$('#todos').before('&lt;div id="profile"&gt;&lt;/div&gt;');

然后使用

隐藏表单

$('#todos').hide();

终于做完了

$('#profile').load(todos.body.loc + '#idOfContentInProfilePage');

在你的 app.post 而不是 res.redirect('/profile') 中,你可以只做res.end({"loc": "/profile"});

如果个人资料页面是一个完全不同的页面,内容和样式完全改变,那么您可能想要重定向。

【讨论】:

    【解决方案2】:

    AJAX 正在刷新页面,因为您在 AJAX 调用的 success 方法中有 location.reload();

    使用AJAXSubmit 按钮调用PHP 文件:

    $("#toDoAjax").click(function()
    {
        var textToSend = $('#toDoText').value;
    
        $.post("locationOfPHPfile",
        {
            toDoText: textToSend
        },
        function(data, status)
        {
            alert("This is what I received: " + data + "\nWith Status: " + status);
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <form id="myForm">
      <input type="text" name="toDoText" id="toDoText" value="" placeholder="Enter here" />
      <input type="submit" name="submitButton" value="Submit with Submit" />
      <input type="button" id="toDoAjax" value="Submit with AJAX" />
    </form>

    在 PHP 文件中:

    <?php
        // For Submit button
        if(isset($_GET['toDoText']))
        {
            // Use proper escaping here like mysli_real_escape_string() if
            // your file is connecting to a MySQL database
            $clean['toDoText'] = $_GET['toDoText'];
    
            // Do something
    
            header('Location: /profile');
            // Always use exit() or die() if you don't want the rest of the
            // code executing after header()
            exit();
        }
    
        // For AJAX button
        if(isset($_GET['toDoAJAX']))
        {
            // Use proper escaping here like mysli_real_escape_string() if
            // your file is connecting to a MySQL database
            $clean['toDoAJAX'] = $_GET['toDoAJAX'];
    
            echo $clean['toDoAJAX'];
        }
    
    ?> 
    

    【讨论】:

      猜你喜欢
      • 2015-07-02
      • 2013-08-23
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-10
      相关资源
      最近更新 更多