javascript - 如何显示回电中需要的内容而不是整个页面

标签 javascript php jquery ajax

我的index.php中有:

<?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);
        }
    }); 
}

这显示了 div 中带有“show”类的整个index.php。我不需要,我只需要该 div 中的“这是有关项目 id: 2 的信息”,没有其他。

我一直在阅读其他类似的帖子,也许我不应该使用 ajax 函数。关于如何做到这一点有什么想法吗?

非常感谢!!

最佳答案

您必须将 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;

关于javascript - 如何显示回电中需要的内容而不是整个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40439309/

相关文章:

javascript - Angular 属性 'parentNode' 在类型 'EventTarget' 上不存在

javascript - 在 componentDidMount() 期间设置状态

php - 在 PHP : ORA-01460: unimplemented or unreasonable conversion requested 中执行存储过程

jquery 表单插件 noConflict 问题

jquery - 房间:362 Uncaught TypeError: Cannot read property 'length' of undefined

javascript - 如何管理 Webpack/Electron 应用程序的配置?

javascript - Phaser缓存加载问题

php - REST 风格的 PHP : how does it work from client side to server side?

php - 将数组从 php 发送到 AJAX 响应

javascript - $ 不是函数。 Backbone 、jQuery 和 Browserify