jQuery函数响应未定义

时间:2019-12-01 07:10:38

标签: jquery

我一直在从事一个项目,最近我遇到了这种奇怪的Jquery行为!

  

代码段

$("#form_1").submit(function (event){
    event.preventDefault();
    response =  sendform('form_1', '../php/signup-01.php', 'POST', '');
    console.log(response.responseText);
});
  

sendform()

function sendform(id, location, method, extrapars) {
    response = $.ajax({
        url : location ,
        data : $("#"+id).serialize() + extrapars ,
        cache : false ,
        processData : false  ,
        type : method ,
        success : function (successmsg) {
            return successmsg;

                }
            });
    return response;
}

因此,基本上,我试图通过预定义的函数发送一些表单数据,但是当我尝试在控制台中记录响应时,它说Undefined。我知道这是一个JS对象,所以我什至尝试使用Console.log(response[responseText])

当我尝试记录完整的对象Console.log(response)时,有点像

abort: ƒ ( statusText )
always: ƒ ()
catch: ƒ ( fn )
done: ƒ ()
fail: ƒ ()
getAllResponseHeaders: ƒ ()
getResponseHeader: ƒ ( key )
overrideMimeType: ƒ ( type )
pipe: ƒ ( /* fnDone, fnFail, fnProgress */ )
progress: ƒ ()
promise: ƒ ( obj )
readyState: 4
responseText: "Unused OTP in DB!"
setRequestHeader: ƒ ( name, value )
state: ƒ ()
status: 200
statusCode: ƒ ( map )
statusText: "OK"
then: ƒ ( onFulfilled, onRejected, onProgress )
__proto__: Object

因此,任何有关这方面的帮助都将对我有所帮助。预先感谢!

1 个答案:

答案 0 :(得分:2)

您可以尝试类似的方法。不管如何处理$.ajax方法的结果,您都可以进一步依赖JQuery,因此可以忘记回调。

function sendform(id, location, method, extrapars) {
    return $.ajax({
        url : location ,
        data : $("#"+id).serialize() + extrapars ,
        cache : false ,
        processData : false  ,
        type : method
    });
}

现在,关于用法,您可以依靠新的async/await

$("#form_1").submit(asnyc function (event){
    event.preventDefault();
    try {
      const response =  await sendform('form_1', '../php/signup-01.php', 'POST', '');
      console.log(response);
   } catch(ex) {
      // handle error
   }
});

或者您可以使用JQquery方式:

$("#form_1").submit(function (event){
    event.preventDefault();
      sendform('form_1', '../php/signup-01.php', 'POST', '')
      .done(function(data, textStatus, jqXHR) {
        console.log(data);
      })
      .fail(function(jqXHR, textStatus, errorThrown) {
       // handle error      
      });      
});

延迟是promise兼容的,因此它们也then可用。