简体   繁体   English

在javascript中捕获php mysql变量

[英]Catching php mysql variable in javascript

Im wondering how to catch mysql row in javascript, i tried to do that this way: 我想知道如何在javascript中捕获mysql行,我试着这样做:

    var  x = <?php 
    mysql_connect(Not important);
    mysql_select_db(not important);
    $zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
    $idzapytania = mysql_query($zapytanie);
    $wiersz = mysql_fetch_row($idzapytania);
    echo $wiersz[0];
    mysql_close (notimportant);
    ?>;

    alert(x);

But this is not working. 但这不起作用。 Any solutions? 有解决方案吗 Sorry if this questions seems to be lame but i not the best in php/js, but have few things to do. 对不起,如果这个问题似乎很蹩脚,但我不是最好的php / js,但有几件事情要做。

You should enclose the output of PHP in single quotes if you want it to be treated as a string in javascript. 如果您希望将其视为javascript中的字符串,则应将PHP的输出括在单引号中。 Like this: 像这样:

var  x = '<?php 
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email=\'$email\'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
echo $wiersz[0];
mysql_close (notimportant);
?>';

Or alternatively, replace echo $wiersz[0]; 或者,替换echo $wiersz[0]; for echo "'". $wiersz[0] ."'"; echo "'". $wiersz[0] ."'"; echo "'". $wiersz[0] ."'";

If you want to pass an array from PHP to jquery/javascript, the best way would be using JSON. 如果要将数组从PHP传递给jquery / javascript,最好的方法是使用JSON。 Pseudocode: 伪代码:

var x=JSON.parse(<?php echo json_encode($array); ?>);

<script type="text/javascript">

setVariables('<?php echo $tag_name ?>', '<?php echo $client_id ?>');

</script>

然后在.js文件中创建该函数以利用这些值并执行您需要的操作。

function setVariables(name, id){ var tag_name = name var client_id = id //Operations that need these values. }

Try this 尝试这个

<?php 
   mysql_connect(Not important);
   mysql_select_db(not important);
   $zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
   $idzapytania = mysql_query($zapytanie);
   $wiersz = mysql_fetch_row($idzapytania);
   $w=$wiersz[0];
   mysql_close (notimportant);
?>;

<script>
 var  x =<?php echo $w ?> 
 alert(x);
</script>

write bundles to javascript! 写捆绑到JavaScript!

Personally whenever transferring initilisation data from PHP to the client I find it best to combine the data into an array, and use casting and json_encode (as per Helpful's answer) to make a final structure that is nice and easy to use on the JavaScript side. 个人每当将初始化数据从PHP传输到客户端时,我发现最好将数据合并到一个数组中,并使用cast和json_encode (根据有用的答案)来创建一个在JavaScript端很好用且易于使用的最终结构。 This saves echoing different variables all over the place, and will automatically handle any type and escape syntax that is required ie wrapping strings with quotes, or back-slashing internal quotes in strings. 这样可以在整个地方保存回显不同的变量,并自动处理所需的任何类型和转义语法,即用引号包装字符串或在字符串中反向缩减内部引号。

<?php

$export = array();

mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
mysql_close (notimportant);

$export['x'] = !empty($wiersz[0]) ? $wiersz[0] : 'default';

?>
var data = <?php echo json_encode((object) $export); ?>;

Obviously the above is a little overkill for just one small value, however, if there ever became more than one value — something that could quite easily happen after further coding — it would be very easy to extend: 显然,对于一个小值,上面的内容有点过分,但是,如果有一个以上的值 - 在进一步编码后很容易发生的事情 - 它将很容易扩展:

$export['x'] = !empty($wiersz[0]) ? $wiersz[0] : 'default';
$export['something_else'] = 54321;

Then all you need do to access these values in JavaScript is: 然后你需要做的就是在JavaScript中访问这些值:

data.x
data.something_else


why use an array and why cast to an object? 为什么要使用数组以及为什么要转换为对象?

The reason why I use an associative Array on the PHP side is because I find writing to arrays cleaner in PHP than Objects — not a huge fan of the -> notation. 我在PHP端使用关联数组的原因是因为我发现在PHP中写入数组比使用对象更清晰 - 而不是->符号的巨大粉丝。 Also instantiating an Array is easier and seemingly more native than an Object in many versions of PHP. 在许多PHP版本中,实例化一个数组比一个对象更容易,看起来更像是本机。 I then cast to an object before writing to JavaScript because I find the opposite is true in JavaScript, it's easier and nicer to read when accessing objects rather than arrays. 然后我在写入JavaScript之前转换为一个对象,因为我发现JavaScript中的情况正好相反,访问对象而不是数组时读取更容易和更好。 This is all personal taste however. 然而,这是个人品味。

NOTE: When defining your keys in the $export array you should be wary to keep to standard variable naming conventions ie either use camelCase/interCaps or convert spaces to underscores. 注意:$export数组中定义键时,您应该谨慎遵守标准变量命名约定,即使用camelCase / interCaps或将空格转换为下划线。 Whilst you can get away with using any characters, even spaces, it will mean accessing the data from the JavaScript side becomes more cumbersome. 虽然您可以使用任何字符,甚至空格,但这意味着从JavaScript端访问数据变得更加麻烦。


another thing to bear in mind 另一件要记住的事情

When setting variables in JavaScript it's often seen as a bad thing to pollute the global namespace . 在JavaScript中设置变量时,通常认为污染全局命名空间是一件坏事。 This basically means writing variables at the top level of run-time, that attach to themselves to global Object (usually Window), so that they are accessible by every bit of JavaScript code that runs in that execution. 这基本上意味着在运行时的顶层编写变量,将变量附加到全局Object(通常是Window),以便在执行中运行的每一段JavaScript代码都可以访问它们。 It is seen as bad because unless you use a likely unique variable name, collisions with other code can occur ie if both bits of code rely on the same global variable. 它被认为是坏的,因为除非您使用可能唯一的变量名称,否则可能会发生与其他代码的冲突,即两个代码位都依赖于相同的全局变量。

If you just output your data var at the top of your script it will become part of the global namespace, and using something as bland as data would be a prime example of something to avoid. 如果您只是在脚本顶部输出数据var,它将成为全局命名空间的一部分,并且使用像data一样平淡的东西将是避免某些事情的主要示例。 It may not matter at all for small projects that aren't going to be extended or worked on by multiple coders, but it is always a good idea to get into the habit of avoiding this. 对于那些不会被多个编码人员扩展或工作的小型项目来说,这可能并不重要,但是养成避免这种情况的习惯总是一个好主意。

You can of course just use a variable name that is more unique to your project eg myProjectData , or if you have an over-arching namespace that defines your project ie examples of which would be jQuery, JSON, console; 您当然可以使用对您的项目更独特的变量名称,例如myProjectData ,或者如果您有一个定义项目的过度命名空间,例如jQuery,JSON,console; you could attach it to that eg Project.data . 你可以将它附加到例如Project.data

However, if you wanted a more general approach you can also do this by wrapping your JavaScript code in an anonymous function. 但是,如果您想要更通用的方法,也可以通过将JavaScript代码包装在匿名函数中来实现。

<?php

$export = array();
$export['random_value'] = 'Where\'s my monkey?';

?>

(function( data ){

  /// data will only be available inside this function
  /// or to other sub functions defined inside this function.
  console.log(data.random_value);

})(<?php echo json_encode((object) $export); ?>);

With the above code you should end up with your JavaScript always having a nice bundle of values to access, properly escaped and formatted, that have come straight from PHP in an easy way, and that doesn't pollute the global namespace. 使用上面的代码,您最终应该总是拥有一个很好的值集来访问,正确转义和格式化,这些值直接来自PHP,并且不会污染全局命名空间。

WARNING: Obviously it should be noted that if you use the above anonymous wrapper method and you call in any other script files within your page, they wont be able to access data unless you pass the object to that code in some way. 警告:显然应该注意的是,如果您使用上述匿名包装器方法并调用页面中的任何其他脚本文件,除非您以某种方式将对象传递给该代码,否则它们将无法访问data This is why people often prefer to have an over-arching namespace object for their project ie MyProject.data . 这就是为什么人们通常更喜欢为他们的项目(即MyProject.data拥有一个过度拱形的命名空间对象。 However you do not necessarily have to do this — due to the benefit of having all your values bundled up in a singular JavaScript object — because passing it to other code is as simple as sending one variable as a parameter to a function ie other.code(data) 但是,您不一定要这样做 - 由于将所有值捆绑在单个JavaScript对象中的好处 - 因为将其传递给其他代码就像将一个变量作为参数发送到函数即other.code(data)一样简单other.code(data)

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

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