简体   繁体   English

Ajax失败了

[英]Ajax is failing

I can't figure out why this Ajax script isnt working. 我不知道为什么这个Ajax脚本不起作用。

Heres the code: 这是代码:

$(document).on('submit', '.edit_user', function(){
    console.log('submit');
    $.post
    (
      $(this).attr('action'),
      $(this).serialize(),
      function(data){
        console.log("data");
        console.log(data);
        $('#edit_first_name').val(data['first_name']);
      },
      "json"
    );
    return false;
  });

I have the submit show up in the console so I know the .post is called. 我在控制台中显示了submit ,所以我知道调用了.post I also know it makes it to the return false because the form never submits and redirects. 我也知道它使它return false因为表单从不提交和重定向。

However, it never console.log(data) . 但是,它永远不会console.log(data)

I'm pretty sure all this is because I'm forgetting something simple. 我很确定所有这一切都是因为我忘记了一些简单的事情。

Try using the .fail() callback and see if it returns, also make sure the server sends the json header properly or $.post will fail. 尝试使用.fail()回调并查看是否返回,还请确保服务器正确发送json头,否则$.post将会失败。

$(document).on('submit', '.edit_user', function(){
    console.log('submit');
    var jqXHR = $.post($(this).attr('action'), $(this).serialize(),
        function(data){
            console.log("data");
            console.log(data);
            $('#edit_first_name').val(data['first_name']);
        },
        "json"
    );
    jqXHR.fail(function(jqXHR, textStatus, errorThrown) {
        console.log('error', textStatus, errorThrown);
    });
    return false;
});

If you're using PHP, make sure you have the correct header printed before any other output. 如果您使用的是PHP,请确保在任何其他输出之前打印正确的标题。

<?php
    header('Content-type: application/json');
    ....code...
    echo json_encode(some_array);

The function you have defined is for the success callback. 您定义的函数用于成功回调。 Make sure your current post is returning a successful response from the server. 确保您当前的帖子正在从服务器返回成功的响应。 Or convert the .post() call to a .ajax() call and define the failure calback 或将.post()调用转换为.ajax()调用并定义失败回溯

Use this, 用这个,

$(document).on('submit', '.edit_user', function(e){
e.preventDefault();
console.log('submit');
$.post
(
  $(this).attr('action'),
  $(this).serialize(),
  function(data){
    console.log("data");
    console.log(data);
    $('#edit_first_name').val(data['first_name']);
  },
  "json"
);
return false;
});

Use preventDefault function to prevent default behaviour of submit. 使用preventDefault函数可防止提交的默认行为。 Also .edit_user should be the class of the form element 另外.edit_user应该是form元素的类

您的JavaScript记录器会返回给您一些东西吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM