1

** 我找到了一种可行的方法 - 将其粘贴在所有这些文本下方**

我想使用 Ajax 使用按钮发送包含 PHP 变量的隐藏值。

如果我定义它,我可以发送值没有问题:

    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
    $(document).ready(function(){
    $("button").click(function(){
    $.post("results.php",
    {
    id:"1000"
    },
    function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
    });
    });
    });
    </script>

然后我可以处理页面results.php 上的$_POST['id'] 变量。

但是如何指示 Ajax 在 HTML 表单按钮中发送隐藏值?我的 HTML 包含在 PHP print_r 指令中,如下所示:

    print("<form id='form' method='post' action=''>
    <input type='hidden' name='id' value=$strTweet2>
    <input type='submit' value='RT'></form>");

感谢溢出者的任何帮助。我一直在阅读其他人的问题,并且学会了如果我定义它就发送一个值,我只是不知道如何从一个按钮发送值。

** 所以我有这个工作,但只能在 HTML 中工作,当我在 foreach 中应用它时,它只会给我数组中的第一个值,但我想我会问另一个问题。此脚本将从表单按钮发送单个隐藏值**

    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
    function submitForm() {
    $.ajax({type:'POST', url: 'results.php', data:$('#ContactForm').serialize()});
    return false;
    }
    </script>

HTML

    <form id='ContactForm' onsubmit='return submitForm();'>
    <input type='hidden' name='id' value='1000'>
    <input type='submit' value='Post it!'>
4

1 回答 1

0

Firstly, do not use print_r() as this function is meant for debugging. Use print() instead.

In jQuery you can access hidden field value by field name like this:

$('input[name=id]').val()

but you can give it id and do this:

$('#id').val()

... and put your string into double quotes:

print("<form id='form' method='post' action=''>
<input type='hidden' name='id' value=$strTweet2>
<input type='submit' value='RT'></form>").

Edit: Working example how to select hidden field value by name and post it using jQuery .post()

<?php

if (!empty($_POST['id'])){
    print(json_encode(array('id' => $_POST['id'])));
    exit();
}

?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){ 
    $('input[type=submit]').click(function(){ 
        $.post("", { id:$('input[name=id]').val() }, function(data,status){ 
            alert("Data: " + data + "\nStatus: " + status); 
        });
        return false;
    }); 
});

</script>

<form id="form" method="post" action="">
    <input type="hidden" name="id" value="hidden_value">
    <input type="submit" value="RT">
</form>

Just copy it into .php file and point your browser there :)

于 2013-08-31T21:48:35.610 回答