如何将整数值传递给 PHP 整数变量中的 JS? [英] How to pass an integer value to JS that is in a PHP integer variable?

查看:31
本文介绍了如何将整数值传递给 PHP 整数变量中的 JS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些变量从 PHP 传递给 JS.

I'm trying to pass some variables from PHP to JS.

我看到 here ,对于字符串,以下代码可以工作:

I saw here that for strings the following code would work:

    var str = "<?php echo $x; ?>";

我一直在使用这个:

    var var1 = <?= $var1 ?>;

我应该为 int 使用哪个?第一个版本总是好的?第二个只是一种旧形式吗?我很乐意提供有关将变量(dif 类型)从 php 传递到 js 的说明和说明.

Which one should I use for int? the first version is always good? Is the second one just an old form? I'd be happy for a clarification and instruction on passing variables (dif types) from php to js in general.

谢谢!

推荐答案

首先,让我们来看看如何在 javascript 中声明变量.

First of all, lets go over how to declare a variable in javascript.

变量有很多种,但让我们来看看 intstring.字符串周围必须有引号.Int 没有.

There are many types of variables, but lets go over int and string. Strings have to have quotation marks around the. Int's don't.

var int = 5;
var string = "hello";

现在,当我们将变量从 php 传递给 javascript 时,我们所做的就是将等号后面的值替换为 php 中声明的变量.您提到了两种回显变量的方法.

Now when we are passing a variable from php to javascript, all we are doing is replacing the value after the equal sign with a variable declared in php. You mentioned the two ways for echoing a variable.

var str = "<?php echo $phpVariable; ?>";
var str = "<?= $phpVariable ?>";

如果这些变量是 int(顺便说一下,它包括任何数字,无论是否为整数),那么 php 开始和结束标记周围将没有引号.现在,您说您更喜欢使用第二种方法.我真的建议你不要.尽管输入 <?= $phpVariable ?> 比输入 <?php echo $phpVariable; 容易得多.?>,前者不是所有服务器都支持,而后者是.您可以根据需要使用它,但如果您想移动到服务器,则需要先检查是否允许使用该语法.

If these variables were int (which by the way includes any number, whether integer or not), there would be no quotation marks around the php open and close tags. Now, you said you prefer using the second method. I would really advise you not to. Even though it is a lot easier to type <?= $phpVariable ?> than <?php echo $phpVariable; ?>, the former one isn't supported on all servers, whereas the latter one is. You can use it if you want, but if you ever want to move to a server, you need to check if that syntex is allowed first.

这篇关于如何将整数值传递给 PHP 整数变量中的 JS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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