简体   繁体   中英

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 .

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

<?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:

  1. URLs that are intended to be directly accessed by the browser, and which return HTML.

  2. URLs that are intended to be accessed using (only) AJAX calls, and which return JSON (or 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). 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.

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. For example you can add contentType: "application/json" , to your jQuery ajax options then you check for $_SERVER["CONTENT_TYPE"] value:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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