简体   繁体   English

Ajax GET返回整个页面或只是PHP响应

[英]Ajax GET returning entire page or just PHP response

From few days I'm trying to make this code work: 从几天开始,我试图使这段代码起作用:

.PHP : .PHP:

if (($_SERVER['REQUEST_METHOD'] === 'GET') && isset($_GET['tkn']) && isset($_GET['t'])) {
    $tkn = $mysqli->real_escape_string($_GET['tkn']);
    $t = $mysqli->real_escape_string($_GET['t']);
    if (time() < $t) {
        $info["msg"]="<strong>Error! </strong>link valid!";
        $info["cls"]="brand";
    }
    else {
        $info["msg"]="<strong>Error! </strong>Link expired!";
        $info["cls"]="danger";
    }
    $mysqli->close();
    json_encode($info);
}

.JS : .JS:

$.ajax({     
    url: window.location.href,
    success: function(response) {
        console.log(response);
    },
    error: function(response) {
        console.log(response);
    },
    dataType: "JSON"
  });

If I use the current PHP code without adding exit(json_encode($info)); 如果我使用当前的PHP代码而不添加exit(json_encode($ info)); It will return the entire html tag without any text returned by PHP code. 它将返回整个html标记,而PHP代码未返回任何文本。

If I'm adding exit(json_encode($info)); 如果我要添加exit(json_encode($ info)); it will display only that code on white background. 它只会在白色背景上显示该代码。

Any ideas? 有任何想法吗? Thanks! 谢谢!

Here's my login.php format 这是我的login.php格式

 <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { //some code goes here echo json_encode($info); exit; // this part is working perfectly, is getting the answer from php via ajax and display it in page(html part in running) } elseif ($_SERVER['REQUEST_METHOD'] === 'GET') { //other code goes here echo json_encode($info); exit; // here is displayed only the message(without html part) if I add exit; //and if i dont add exit is displayed the message on white background on // the top of the page(html part is working); ?> //html part 

You need to print the json string after all 您毕竟需要打印json字符串

use 采用

echo json_encode($info);

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

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