如何将php发布数据传递给javascript [英] Ways to pass php post data to javascript
问题描述
< form action =index2.phpmethod =post >
< input name =sugarclass =formtype =textvalue =/>
< input name =fatclass =formtype =textvalue =/>
< input name =proteinclass =formtype =textvalue =/>
< input type =submitvalue =submit/>
< / form>
其次是:
<?php
$ sugar = $ _POST ['sugar'];
$ fat = $ _POST ['fat'];
$ protein = $ _POST ['protein'];
?>
< html>
< head>
< script src =http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.jstype =text / javascript>< / script>
< script type =text / javascript>
var sugar =<?php echo $ sugar?>;
var fat =<?php echo $ fat?>;
var protein =<?php echo $ protein?>;
< / script>
< script src =test.jstype =text / javascript>< / script>
< / head>
有人对我可以遵循的替代方案有任何建议吗?我一直没有使用JavaScript太长时间,所以在处理这种情况时,我很高兴知道我的选择。
最简单的方法就是发送一个包含你发送的所有数据的Javascript对象。这可以通过JSON编码轻松完成 $ _ POST
:
var data =<?php echo json_encode($ _ POST)?>;
然后,您就可以访问 data.fat </ code>如果您在POST请求中发送了
fat </ code>值。
So I was wondering, if I have a simple php form that posts information to a certain variable, how can I pass that posted variable to javascript and be able to manipulate the data? The only way I've figured out is by using inline javascript with php but I feel there must be a cleaner and more elegant way to do it where the variables don't show up so blatantly in the source code and are handled externally.. Here's what I'm playing around with right now:
<form action="index2.php" method="post">
<input name="sugar" class="form" type="text" value="" />
<input name="fat" class="form" type="text" value="" />
<input name="protein" class="form" type="text" value="" />
<input type="submit" value="submit" />
</form>
Which is followed by:
<?php
$sugar = $_POST['sugar'];
$fat = $_POST['fat'];
$protein = $_POST['protein'];
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var sugar = "<?php echo $sugar ?>";
var fat = "<?php echo $fat ?>";
var protein = "<?php echo $protein ?>";
</script>
<script src="test.js" type="text/javascript"></script>
</head>
Does anyone have any suggestions for alternatives I could follow? I haven't been using javascript for too long so it would be nice to know my options when dealing with a situation such as this.
The easiest way to do this would be simply to send a Javascript object containing all the data you sent. This can easily be accomplished by JSON-encoding $_POST
:
var data = <?php echo json_encode($_POST) ?>;
You can then access, for instance, data.fat
if you sent a fat
value in your POST request.
这篇关于如何将php发布数据传递给javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!