将变量从PHP发送到Javascript [英] Send variable from PHP to Javascript

查看:95
本文介绍了将变量从PHP发送到Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个单独的文件中有以下代码,其中一个是javascript,另一个是php:

I have the following code in two separate files, one of them javascript and the other php:

Javascript

Javascript

xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
       document.getElementById("dummy").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","getgames.php?yearFilter="+yearFilter,true);
  xmlhttp.send(null);

php

$yearFilter = (int)$_REQUEST["yearFilter"];
$dummyvariable = 123245;

我一直在使用javascript文件将变量传递给php,但我无法弄清楚如何发送从php返回到javascript文件的变量(例如虚拟变量示例)。我知道结果应该以this.responseText结尾但我不知道在php文件中放入什么代码以便将其发送到那里。谁能帮我这个?我对这些语言比较陌生,所以如果示例尽可能简单,我将不胜感激。

I have been using the javascript file to pass variables to php but I cannot figure out how to send a variable (such as the dummyvariable example) from php BACK to the javascript file. I know that result should end up in "this.responseText" but I don't know what code to put in the php file in order to send it there. Can anyone help me with this? I am relatively new to these languages so I would appreciate if examples be as simple as possible.

推荐答案

您正在使用的方法可以工作,但我不推荐它,因为并不总是你需要传递一个变量,有时可能是一个数组或一个对象,谁知道。我将告诉你如何做到但是使用jQuery已经有一段时间了,因为我使用纯javascript进行ajax调用,所以如果你不能使用jQuery你需要翻译它:)

The approach that you are using could work but I don't recommend it because not always you need to pass just a variable, sometimes could be an array or a object, who knows. I will show you how to do it but with jQuery it's been a while since I use pure javascript for an ajax call so if you can't use jQuery you need to translate it :)

PHP部分

$data = [
    'dummyvariable' => '12345'
];
echo json_encode($data);

Javascript Part

Javascript Part

$.ajax({
    url: 'getgames.php',
    type: 'get',
    data: {
        'yearFilter': yearFilter
    },
    dataType: 'json',
    success: function(data){
        $("#dummy").html(data.dummyvariable)
    }
});

这样你可以传递更多的变量,它会更有条理,你也可以做像你发布的PHP,在这种情况下,你可以只使用数据变量。

This way you can pass a lot more of variable, and it will be more organized, you can also do the php like you post it and in that case you can just use the data variable.

此外,PHP和Javascript中的变量数据的名称,它没有作为数据它只是我的第一个名字。

Also the name of the variable data in PHP and Javascript it doesn't has to be data it just the first name that occurs me.

这篇关于将变量从PHP发送到Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆