简体   繁体   English

如果ajax调用,则返回json,否则返回html

[英]return json if ajax call otherwise return html

I try to a find a method to return a json if it is a ajax call else I want the HTML . 我尝试找到一种方法来返回json,如果它是一个ajax调用,否则我想要HTML。

I am not using a framework or a templating ... 我没有使用框架或模板...

this is what I done in my first page 这是我在第一页中所做的

$.ajax({
    type : 'GET',
    dataType: 'json',
    url : 'XXXXX.php',
    data : {'id' : id_test },
    cache : false , 
    success : function(html) {
        console.log(html);
    }
})

And in my XXXXX.php page I have 在我的XXXXX.php页面中,

<?php
    $my_id = $_GET['id'];
    if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        ....
        return json_encode($my_value);
    } else {
        ?>
        <html>
            <head>
                <title></title>
            </head>
            <body>
                bla bla ba bla bla
            </body>
        </html>
        <?php
    }    
?>

I am not sure I am using the good solution. 我不确定我使用的是好的解决方案。

Ordinarily, there are two (distinct ...) sets of URLs that the host provides: 通常情况下,有两个 (不同的...)两组URL的主机提供:

  1. URLs that are intended to be directly accessed by the browser, and which return HTML. 旨在由浏览器直接访问并返回HTML的URL。

  2. URLs that are intended to be accessed using (only) AJAX calls, and which return JSON (or XML). 旨在使用(仅)AJAX调用访问的URL,它们返回JSON(或XML)。

URLs in the second group are strictly for program-to-program communication: the technique is sometimes formally referred to as Remote Procedure Calls (RPC). 第二组中的URL严格用于程序间通信:该技术有时被正式称为远程过程调用(RPC)。 A (JavaScript) program on the client side is talking to another program on the host side, and then programmatically acting upon the response in some way. 客户端上的(JavaScript) 程序正在与主机上的另一个程序进行通信,然后以某种方式对响应进行编程

While your technique could work, and superficially seems to me to be correctly coded, I have almost never actually seen it done and would not recommend it. 虽然你的技术可以工作,并且表面上似乎对我正确编码,我几乎从未真正看到它完成,不会推荐它。

$_SERVER['HTTP_X_REQUESTED_WITH'] is the correct way but not all servers/frameworks provide this variable so having other checks in place will be important. $_SERVER['HTTP_X_REQUESTED_WITH']是正确的方法,但并非所有服务器/框架都提供此变量,因此进行其他检查很重要。 For example you can add contentType: "application/json" , to your jQuery ajax options then you check for $_SERVER["CONTENT_TYPE"] value: 例如,您可以将contentType: "application/json"添加到jQuery ajax选项中,然后检查$_SERVER["CONTENT_TYPE"]值:

if($_SERVER["CONTENT_TYPE"] === 'application/json') {
     //....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM