2015-06-14 30 views
-1

我對PHP腳本進行了AJAX調用,該腳本返回Bootstrap3模式或HTML表單的內容。在採取行動之前檢查AJAX響應數據

PHP代碼 - (ajax.php):

if ($numLegs == 1) { 
    echo $formData; 
} else { 
    echo $modalContent; 
} 

如果返回$ FORMDATA,我想顯示的表單數據,如果返回$ modalContent,我想顯示的模式。 如何在決定採取何種行動之前檢查回覆數據?

這是我的代碼 - 它顯示了模式窗口與來自AJAX調用的$ modalContent。但是,在決定採取什麼行動之前,我可以先檢查AJAX響應數據嗎?

<script> 
// By default, modal window is hidden 
$('#myModal').modal({show:false}); 

// This is the function when the button is clicked 
function ajaxCall() { 

    var date = $('.pull-info').parent().prev().prev().children(':input').val(); 
    var num = $('.pull-info').parent().prev().children(':input').val(); 

    $.get( 
     "ajax.php", 
     { date: date, 
     num: num }, 
     function(response) { 
     // HOW DO I CHECK THE RESPONSE BEFORE TAKING THE RELEVANT ACTION???! 
     $(".modalBody").html(response); 
     $(".modalHeader").text(num); 
     $('#myModal').modal('show'); 
     } 
    ); 
} 
</script> 

謝謝!

+0

說哪一個使用更多的變量。類似於'if(response.type =='modal'){//模態代碼}' – vinayakj

+0

'$ numLegs'是如何設置的?它是關於'num'客戶端設置的嗎? –

回答

0

我將返回json串,具有標誌是什麼類型的內容是:

if ($numLegs == 1) { 
    echo json_encode(['type' => 'form', 'content' => $formData]); 
} else { 
    echo json_encode(['type' => 'modal', 'content' => $modalContent]); 
} 

,然後在JS:

$.getJSON("ajax.php", { date: date, num: num }, 
    function(response) { 
     // HOW DO I CHECK THE RESPONSE BEFORE TAKING THE RELEVANT ACTION???! 
     if (response.type == 'form') { 
      $('.form').html(response.content); 
     } else if (response.type == 'modal') { 
      $(".modalBody").html(response.content); 
      $(".modalHeader").text(num); 
      $('#myModal').modal('show'); 
     } 
    } 
); 
+0

謝謝你的幫助!它現在有效。 – GilB

0

這取決於響應數據的格式。

如果格式爲JSON您可以直接比較您正在查找的條件。

否則嘗試將其解析爲JSON並應用相同的條件。

0

我認爲在這種情況下,您必須從服務器返回JSON數據,而不是原始HTML。所以,你的PHP代碼將是:

if ($numLegs == 1) { 
    echo json_encode(array('html' => $formData, 'type' => 'form')); 
} else { 
    echo json_encode(array('html' => $modalContent, 'type' => 'modal')); 
} 

而且在JavaScript方面,你可以檢查response.type並顯示你想要什麼。而response.html將包含HTML的模式或形式

0

你要從你的PHP返回JSON。您可以通過在PHP數組上運行json_encode來完成此操作。像這樣:

$responseArray = array(); 

if ($numLegs == 1) { 
    $responseArray['data'] = $formData; 
    $responseArray['type'] = 'form'; 
} 
else { 
    $responseArray['data'] = $modalContent; 
    $responseArray['type'] = 'modal'; 
} 

echo $responseArray; 

從那裏,你想你的JavaScript來檢測傳遞到響應的type參數:

$.get( 
    "ajax.php", 
    { date: date, 
    num: num }, 
    function(response) { 

    if (response.type === 'form') { 
     // do form stuff 

    } 
    else if (response.type === 'modal') { 
     // do modal stuff 

    } 

    } 
); 
0

響應本身設置一個試試這個

$.get(´ajax.php´).then(function(res){ 
console.log(res) 
}) 
相關問題