【问题标题】:How to load the content using ajax call and normal php call?如何使用 ajax 调用和普通 php 调用加载内容?
【发布时间】:2012-07-31 00:35:37
【问题描述】:

我已经为 php 页面创建了 jquery-ajax 调用,该页面通过根据从第一页接收到的 id 从数据库中选择数据来创建内容

当我点击 person1 时,第一页 index.php 有链接 person1,它通过 jquery 重定向到详细信息页面这里是代码:

 $('.details').click(function() { 
        $("a").removeClass("active");
        $(this).addClass("active"); 
             var id = $(this).attr("id");
              $.ajax({  
                type: "GET",  
                url: "details.php",
                data:{pid:id},
                success: function(html){        
                    $("#persons").html(html).fadeIn(1000);

                }  
            }); 

                 return false;  
        });

内容将在此处加载到 index.php 文件中:

<div class="row">
    <div class="twelve columns" id="persons" style="display:none" >

    </div>
</div>

详情页内容:

   <?

    if(isset($_GET['pid'])){
$id=(int)$_GET['pid'];
    $sql="select id, name,title,details,image,cat from persons  where id ='".$id."' order by name asc";
    $rs=mysql_query($sql)or die(mysql_error());
    if(list($id,$name,$title,$details,$image,$cat)=mysql_fetch_array($rs)){
  ?>
    <h3><? echo $name;?></h3>
    <h5><? echo $title;?></h5>
    <p align="justify">
        <img alt="<? echo $name;?>" src="images/persons/<? echo $image?>" title="<? echo $name;?>" style="float:right; margin-left:15px;" />
        <? echo $details;?>
    </p>
    <?
    }
    }
?>

如何检查页面是通过 ajax 调用还是正常的 php 调用请求的?如果不是ajax调用,是否正常加载详情页内容?

【问题讨论】:

    标签: php ajax


    【解决方案1】:

    您可以检查以下变量:

    $_SERVER['HTTP_X_REQUESTED_WITH']
    

    对于 AJAX 请求,它应该是 'xmlhttprequest'。

    但是,您可以简单地在 URL 中添加一个参数:

    url: "details.php?thisisanajaxrequest=1",
    

    只需检查 URL 变量。

    【讨论】:

    • 以及如何将内容加载到div中以防正常调用不是ajax?
    • 我不太明白您所说的“正常通话”是什么意思。大多数情况下是这样的: - 你有一个可以从 AJAX 调用的页面,或者只是使用它的 URL - 页面代码中的第一件事是检查它是否是 AJAX 调用 - 如果是是 AJAX 调用,只提供相关内容(顺便说一句,这通常是 JSON 编码的) - 如果是常规调用,则呈现页面在您的情况下,这意味着呈现整个页面,同时也填充 DIV来自 PHP。
    • 如果你想在页面第一次加载时填充你的 div,只需在 body onload 时发出一个 ajax 调用,或者你可以只是 file_get_contents 的 URL。
    猜你喜欢
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 2021-04-29
    • 2011-06-17
    • 2012-01-18
    相关资源
    最近更新 更多