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


Assigning textbox value to php variable without using form

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

所以我想要另一种方法。

阿贾克斯,除了是希腊神话中的特洛伊战争英雄......是您需要的技术,也是您的朋友。

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

正如马克斯阿特所指出的,实际上有两个名叫"阿贾克斯"的希腊英雄,他们都参加了特洛伊战争(而且都在荷马的《伊利亚特》中)。


你可以像这样使用 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>

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

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

请务必验证请求方法,例如:

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

并且还要验证和清理输入。如果需要会话,也要验证。无论服务器返回什么,都将在客户端接收。

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

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

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

});

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