2015-02-09 77 views
0

我不确定为什么我的ajax请求的error:部分也在触发。成功和错误部分实际上都是射击。我对JS/jQuery相当陌生,但是当ajax请求成功并且出错时触发错误时,我读取了成功。我假设成功意味着200,错误意味着400-500?AJAX触发成功和错误

JS:

function create_post() { 
     console.log("create post is working"); 
     var firstName = document.getElementById("firstname"); 
     var lastName = document.getElementById("lastname"); 
     var email = document.getElementById("email"); 
     var phoneNumber = document.getElementById("phonenumber"); 
     var message = document.getElementById("message"); 
     var contactInfo = { 
      "first_name": firstName.value, 
      "last_name": lastName.value, 
      "email": email.value, 
      "phone_number": phoneNumber.value, 
      "message": message.value 
     }; 

     $.ajax({ 
      url: "", 
      type: "POST", 
      data: contactInfo, 
      success: ajaxSuccess(contactInfo), 
      error: console.log("ajax fail") 

     }); 
    }; 


    function ajaxSuccess(contactInfo) { 
     console.log(contactInfo); 
     // clear form data 
     document.getElementById("contact-form").reset(); 
     // display modal 
    } 


// Contact form submit 
    var contactForm = document.getElementById("contact-form"); 
    $(contactForm).on('submit', function(event) { 
     event.preventDefault(); 
     console.log("form submitted"); 
     create_post(); 
    }); 

enter image description here

回答

5

您是调用功能,通过他们返回值successerror。你需要传递实际的功能。

因为在这两种情况下,您都对函数的参数进行硬编码,所以可以使用bind来创建新函数。

success: ajaxSuccess.bind(window, contactInfo), 
error: console.log.bind(console, "ajax fail") 
5

你的问题是,在这些线路上:

success: ajaxSuccess(contactInfo), 
error: console.log("ajax fail") 

这将有效地立即同时运行的功能,并设置这些函数的返回值的successerror性能。尝试使用匿名回调函数。

success: function() { 
    ajaxSuccess(contactInfo); 
}, 
error: function() { 
    console.log("ajax fail"); 
} 
+0

感谢您的帮助。但是,现在我的代码始终运行成功部分。但是,我目前没有后端返回任何状态代码,因此可能是问题所在。什么返回码会导致错误部分触发?我假设400s-500s? – Liondancer 2015-02-09 16:08:22

+0

@Liondancer'url:“”'将导致它再次请求当前页面,这可能存在并且以成功状态码进行响应。 – 2015-02-09 16:10:08

+0

这是正确的答案。成功和错误应该是功能。错误回调函数返回三个参数:'jqXHR','textStatus','errorThrown',可用于将错误传递给用户。 – Avraham 2017-05-25 23:33:10