簡體   English   中英

響應總是整個 ajax 數據包

[英]Response always whole ajax-packet

我總是得到整個 ajax 數據包而不是簡單的響應(真/假)作為這個函數的返回(responseJSON.success/responseText.success)。 否則,瀏覽器會向我發送帶有描述內容的錯誤或故障結果

 function isUnique(inputObject) { let type = $(inputObject).attr('id'); let res = $.ajax({ url: '/dbajax.php', method: 'POST', data: {[type]: $(inputObject).val()}, dataType: 'JSON', success: function(data) { return data }, error: function(data) { } }) console.log(res.responseJSON.success); // -> error: Cannot read property 'success' of undefined console.log(res.responseJSON); // -> undefined return res; }
 <?php require('db/dbqueries.php'); if(isset($_POST['username'])){ $login_username = select_login_where_username ($_POST["username"]); echo json_encode(array('success' => empty($login_username),)); } if(isset($_POST['email'])){ $profile_email = select_profile_email_where_email ($email); echo json_encode(array('success' => empty($profile_email),)); } ?>

您的問題與 $.ajax 是異步的事實有關。 所以如果你在 $.ajax 之后寫一些東西,它會在請求被處理之前完成。 你應該在成功函數中做所有事情。

 function isUnique(inputObject) { let type = $(inputObject).attr('id'); let res = $.ajax({ url: '/dbajax.php', method: 'POST', data: {[type]: $(inputObject).val()}, dataType: 'JSON', success: function(data) { console.log(data)}, error: function(data) { console.log(data) } }) }
 <?php require('db/dbqueries.php'); if(isset($_POST['username'])){ $login_username = select_login_where_username ($_POST["username"]); echo json_encode(array('success' => empty($login_username),)); } if(isset($_POST['email'])){ $profile_email = select_profile_email_where_email ($email); echo json_encode(array('success' => empty($profile_email),)); } ?>

您正在嘗試在 ajax 請求完成之前訪問 responseJSON。 您需要等待 ajax 完成才能使用它。 有兩種方法可以做到這一點 -

正如 robinvrd 所提到的,使用成功和錯誤函數:

function isUnique(inputObject) {
    let type = $(inputObject).attr('id');
    let res = $.ajax({
      url: '/dbajax.php',
      method: 'POST',
      data: {[type]: $(inputObject).val()},
      dataType: 'JSON',
      success: function(data) { 
          console.log(data.success); //this will fire when the ajax request is finished and return the data
      },
      error: function(data) {
         console.error(data); //this will tell you of any errors after the request has been made
     }
    })
    return res;
}

或在請求對象上使用回調:

function isUnique(inputObject) {
    let type = $(inputObject).attr('id');
    let res = $.ajax({
      url: '/dbajax.php',
      method: 'POST',
      data: {[type]: $(inputObject).val()},
      dataType: 'JSON'
    })

    res.done(function(result) {
       console.log(res.responseJSON.success); 
    });

    res.fail(function( jqXHR, textStatus) {
       console.error("Request failed: " + textStatus);
    });

    return res;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM