简体   繁体   English

隐藏形式的javascript变量到另一个php脚本

[英]javascript variable in hidden form to another php script

I am sending a javascript value in a hidden form to a php script. 我正在以隐藏形式将javascript值发送到php脚本。 This is the code. 这是代码。

<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function(e) {
var mydata = 3;
if ($(this).is(':not([data-submit="true"])'))
{
        $('form').append('<input type="hidden" name="foo" value=mydata>');
        $('form').data('submit', 'true').submit();
        e.preventDefault();
        return false;
}
})
})

In my php script, I am accessing the value like below. 在我的PHP脚本中,我正在访问以下值。

$src1= $_POST['foo'];
echo $src1;

I have initialized mydata to 3. I am expecting the output to be 3 in my php script, but instead I am getting the string mydata . 我已经将mydata初始化为3。我期望在我的php脚本中输出为3,但是我却得到了字符串mydata

Use this: 用这个:

  $('form').append('<input type="hidden" name="foo" value="'+mydata+'">');

Here mydata is consider as variable not String. 在这里,mydata被视为变量而不是String。

您没有正确连接字符串,请尝试以下方式:

$('form').append('<input type="hidden" name="foo" value="' + mydata +'">');

All the problem was that you was passing mydata as string instead of as the variable itself, you need to concatenate correctly to pass the Value to the Value, as it works. 所有问题是您将mydata作为字符串而不是作为变量本身传递,因此需要正确连接以将Value传递给Value,因为它可以正常工作。

Using this Code: 使用此代码:

<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function(e) {
var mydata = 3;
if ($(this).is(':not([data-submit="true"])'))
{
        $('form').append('<input type="hidden" name="foo" value="'+mydata+'">');
        $('form').data('submit', 'true').submit();
        e.preventDefault();
        return false;
}
})
})

You see that now, the real value into value="" html attribute of the <input> will be 3 instead of "mydata" . 您现在看到, <input> value="" html属性的实际值将是3而不是"mydata"

This way you will be able to access $_POST['foo']; 这样,您将可以访问$_POST['foo']; on the php page, getting 3 . 在php页面上,获取3

JavaScript strings do not interpolate variables. JavaScript字符串不插值变量。 They can't - JavaScript identifiers do not start with sigils, so there is no way to distinguish a variable name in a string from a piece of text. 它们不能-JavaScript标识符不是以sigils开头的,因此无法将字符串中的变量名与一段文本区分开。

The quick, dirty and unsafe approach is to break apart your string and concatenate it: 快速,肮脏和不安全的方法是分解字符串并将其连接起来:

$('form').append('<input type="hidden" name="foo" value="' + mydata + '">');

But this will fail if mydata contains a " and could give weird results if it contains a & , so build you HTML using DOM (or jQuery wrappers around that). 但是,如果mydata包含" ,则失败,并且如果包含& ,则可能会给出怪异的结果,因此请使用DOM(或围绕该jQuery的包装器)构建HTML。

$('form').append(
    $('<input>').attr('type', 'hidden').attr('name', 'foo').attr('value', mydata)
);

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

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