我的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/