2015-06-14 26 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) 
}) 
相关问题