简体   繁体   English

使用JSON,将变量从php传递到javascript

[英]Using JSON, passing variable from php to javascript

I wonder why is it not working? 我不知道为什么它不起作用?

check_login.php check_login.php

<?php
session_start();
$data = array("username" => "true");
echo json_encode($data);
?>

my js file var linkName; 我的js文件var linkName;

$.ajax({
    type: "POST",
    url: "check_login.php",
    dataType: "json",
    success: function(json){
    if(json.username != "true")
    {
      //do something
    }
    }
});

I am trying to get the username after checking whether or not the user has signed in yet in the php file, something like passing a session variable. 我正在尝试检查用户是否已在php文件中登录后获取用户名,类似于传递会话变量。 But currently passing a string seems to already have a problem. 但是当前传递字符串似乎已经有问题。 Any know what I did wrong here? 有人知道我在这里做错了吗?

Still not working the code above. 仍然无法正常工作上述代码。 Anyone want to help me out here? 有人要帮我吗?

You have an error in your PHP code. 您的PHP代码中有错误。 The square bracket ] is not needed in line 3. And, of course you should use echo json_encode($data); 第3行不需要方括号]。当然,您应该使用echo json_encode($ data);。

    `if(json.data.username != "true")` is wrong you do not have data object

    `if(json.username != "true")` try this

You should echo the json data so that the page you get using ajax contains the string data. 您应该回显json数据,以便使用ajax获得的页面包含字符串数据。

<?php
session_start();
$data = array("username" => "true");
echo(json_encode($data));
?>

$.ajax({
    type: "POST",
    url: "check_login.php",
    dataType: "json",
    success: function(json){
       console.log(json)
    }
});

Also some times you might need to set the content type of the header in php to json. 另外有时候,您可能需要将php中标头的内容类型设置为json。

try to send the header 尝试发送标题

header("Content-Type: application/json", true);
print json_encode($data);
 return json_encode($data);

我认为您必须返回数据,而不仅仅是json编码!

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

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