javascript
  • php
  • jquery
  • ajax
  • ajax-success
  • 2016-11-05 21 views 0 likes 
    0

    我在我的index.php:如何顯示所需要的retun調用,而不是整個頁面

    <?php 
    $sContent.='<script src="https://code.jquery.com/jquery-1.12.4.js"></script>'; 
    $sContent.='<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>'; 
    $sContent.='<script src="in.js" type="text/javascript"></script>'; 
    
    $id=2; 
    $sContent.='<div id="agree">Agree to terms: <input type="checkbox" id="agreed" value=1></div>'; 
    $sContent.='<br><br><div class="show"></div>'; 
    
    if($_GET['f'] == 'showInfo') 
    { 
        $sContent.= 'This is the info about item id: '.$_GET['id']; 
    } 
    
    $sAction = $_SERVER['PHP_SELF']."?id=".$id."&f=showInfo"; 
    $sDest.= '<br><input class="'.$id.'" type="button" id="'.$id.'" name="'.$id.'" value="Click to show info about item '.$id.'" onClick="javascript:showInfo(\''.$sAction.'\');">'; 
    
    $sContent.= $sDest; 
    echo $sContent; 
    ?> 
    

    在我的js文件:

    function showInfo (action) 
    { 
    
        var aryAction = action.split('?'); 
        params = aryAction[1]; 
        var theUrl = 'index.php'; 
        alert(aryAction[1]); 
        $.ajax ({ 
         url: theUrl, 
         data: params, 
         async:true, 
         success: function (data, textStatus) 
         { 
          $('.show').html (data); 
         } 
        }); 
    } 
    

    這說明整個索引.php與類'show'的div。我不想要thant,我只需要'這是關於item id:2'的信息,沒有別的。

    我一直在閱讀其他類似的帖子,也許我不應該使用ajax函數,關於如何做的任何想法?

    非常感謝!

    +0

    你就不能改變PHP來只有你想要什麼回報?或者,只有在收到整個頁面後,才需要使用jQuery來提取該部分 – charlietfl

    回答

    1

    您必須將HTML內容與字符串分開。

    把這兩樣東西在if/else條款,那麼它會工作:

    <?php 
    $sContent = ''; 
    if($_GET['f'] == 'showInfo') 
    { 
        $sContent .= 'This is the info about item id: '.$_GET['id']; 
    } 
    else 
    { 
        $sContent .= '<script src="https://code.jquery.com/jquery-1.12.4.js"></script>'; 
        $sContent .= '<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>'; 
        $sContent .= '<script src="in.js" type="text/javascript"></script>'; 
    
        $id=2; 
        $sContent .= '<div id="agree">Agree to terms: <input type="checkbox" id="agreed" value=1></div>'; 
        $sContent .= '<br><br><div class="show"></div>'; 
    
        $sAction = $_SERVER['PHP_SELF']."?id=".$id."&f=showInfo"; 
        $sDest .= '<br><input class="'.$id.'" type="button" id="'.$id.'" name="'.$id.'" value="Click to show info about item '.$id.'" onClick="javascript:showInfo(\''.$sAction.'\');">'; 
    
        $sContent .= $sDest; 
    } 
    echo $sContent; 
    
    相關問題