在不使用表单的情况下将文本框值分配给php变量

时间:2012-06-01 09:04:27

标签: php

我想检索文本框值并将其分配给php变量但不使用表单。我正在做搜索功能,我想隐藏点击按钮上的一些内容,并在同一个点击想要搜索功能,但如果我使用表单,那么它将重定向到另一个页面或再次重新加载我不想要的页面。

所以我想要另外一种方法。

4 个答案:

答案 0 :(得分:2)

除了希腊神话中的木马战争的英雄之外,阿贾克斯是你需要的技术,也是你的朋友。

我建议使用jQuery [因为Barry发布的速度比我快,因为我想确保我的神话参考正确...]

正如MaxArt所指出的那样,实际上有两个名为“阿贾克斯”的希腊英雄,他们都参与了特洛伊战争(以及荷马的伊利亚特)。


您可以像这样使用jQuery:

<!-- Link jQuery (replace src with the location where you have jQuery) -->

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js">
</script>

<!-- Try something like this [having jQuery linked]: -->

<script type="text/javascript">
     function doButtonStuff()
     {
         //Use jQuery to "hide some contents"
         $('#stufftohideId').hide(); //stufftohideId identifies what to hide

         //set the url of the web page that will take this info on your server
         var ulr = "http://localhost";

         //The following part will fail if you cannot connect to the server
         $.post(
             url,
             {text: $('#textboxId').val()}, //textboxId identifies the textbox
             function (data)
             {
                 //data is what the server responded
                 //do something with data, for instance:
                 alert(data);
             }
         );
     }
</script>


<input type="text" id="textboxId"></input>
<input type="button" onclick="doButtonStuff();" value="Click Me"></input>

<div id="stufftohideId">
    <p>
        This is an example of something to hide.
    </p>
</div>

您将进入网页的服务器端,其中包含您传递的网址,如下所示:

<?php $text = $_POST['text']; ?>

确保验证请求方法,例如:

<?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        $text = $_POST['text'];
        //do something with $text, for instance:
        echo $text;
    }
?>

还要验证和消毒输入。如果需要会话,请验证。无论服务器返回什么,都将在客户端收到。

答案 1 :(得分:1)

如果您不想重新加载页面,请查看AJAX,例如jQuery:http://api.jquery.com/jQuery.ajax/

答案 2 :(得分:1)

您可以使用PHP的ajax实现来阻止页面重新加载或重定向。你可以检查CakePHP,tppAjax ......

答案 3 :(得分:1)

$(document).ready(function() {

    $("#textboxID").change(function(){
        var text = $(this).val();
    });

});

使用jQuery,您可以在文档就绪函数中使用.change方法来获取文本字段值。一旦你通过jquery获得了值,你就可以执行一些ajax并将javascript变量发送到一个php页面,在那里你可以使用$ _GET方法来获取它,此时你在php中有你的变量你就可以做任何你想做的事情用它。