无法使用AJAX将PHP变量传递给JavaScript文件

时间:2021-07-13 22:46:26

While looking at tons of examples of how to get a PHP variable sent to a JavaScript file, I still haven't had success getting it.

在查看大量如何将PHP变量发送到JavaScript文件的示例时,我仍然没有成功获得它。

My PHP file is:

我的PHP文件是:

$title = $json["title"];

echo json_encode($title);

And my JavaScript file app.js is:

我的JavaScript文件app.js是:

$.ajax({
            url : 'index.php',
            type : 'GET',
            data : film,
            dataType : 'json',
            success : function (data) {
                alert(data.title);
                console.log(data.title);
            },
        })

I would like to know the right code to get the PHP $title variable to the ajax call in app.js.

我想知道正确的代码,以获得app.js中的ajax调用PHP $ title变量。

Thanks

谢谢

2 个解决方案

#1


2  

For this example there are two files. One has the JQuery ajax method. The other file is a PHP script that returns the requested information.

对于此示例,有两个文件。一个有JQuery ajax方法。另一个文件是一个返回所请求信息的PHP脚本。

show_title.html

show_title.html

<!-- JQuery library already loaded -->
<script>

$.ajax({
    url : 'get_title.php', // requesting a PHP script
    dataType : 'json',
    success : function (data) { // data contains the PHP script output
       alert(data.title);
       console.log(data.title);
    },
})

</script>

get_title.php

get_title.php

<?php

$json["title"] = 'a title';
echo json_encode($json);

?>

#2


2  

If you'd want a .title property on the response, then you should create an array then encode that instead. You got the other way around. Something like this:

如果您想在响应上使用.title属性,那么您应该创建一个数组,然后对其进行编码。你反过来了。像这样的东西:

PHP

PHP

<?php

$title = 'Yahoo!';
$json['title'] = $title;
echo json_encode($json);

#1


2  

For this example there are two files. One has the JQuery ajax method. The other file is a PHP script that returns the requested information.

对于此示例,有两个文件。一个有JQuery ajax方法。另一个文件是一个返回所请求信息的PHP脚本。

show_title.html

show_title.html

<!-- JQuery library already loaded -->
<script>

$.ajax({
    url : 'get_title.php', // requesting a PHP script
    dataType : 'json',
    success : function (data) { // data contains the PHP script output
       alert(data.title);
       console.log(data.title);
    },
})

</script>

get_title.php

get_title.php

<?php

$json["title"] = 'a title';
echo json_encode($json);

?>

#2


2  

If you'd want a .title property on the response, then you should create an array then encode that instead. You got the other way around. Something like this:

如果您想在响应上使用.title属性,那么您应该创建一个数组,然后对其进行编码。你反过来了。像这样的东西:

PHP

PHP

<?php

$title = 'Yahoo!';
$json['title'] = $title;
echo json_encode($json);