2016-03-14 78 views
0

我觉得这是一个常见的问题,但我没有找到一个合适的答案,所以我请你吧! ;)PHP,形式,重定向和查询

让我们先从经典的index.php形式:

... 
    <form action="<?php echo BASE_URL; ?>"> 
     <div style="color:white">Instructions</div> 
     <input type="number" name="param" /> 
     <input type="hidden" name="action" value="view" /> 
     <input type="hidden" name="controller" value="Solution" /> 

     <input type="????" name="instance_id" value="?????" /> 

     <input type="submit" value="Solutions Listing" id="button_solutions"> 
    </form> 
... 

这里的问题是,提交按钮前的最后输入场。假设用户在第一非隐藏输入法输入PARAM,并应触发一个PHP函数,通过挑选到数据库中确定INSTANCE_ID

我想要做的是,当用户点击提交,它通过链接重定向

BASE_URL."?controller=Solution&action=view&param=toto&instance_id=value" 

比方说,我在PHP函数挑到数据库称为TOTO() toto返回instance_id。 我知道如何通过表单,我不知道该怎么触发PHP函数与GET参数指向的URL。 我知道如何通过帕拉姆输入确定INSTANCE_ID 我不知道如何通过PHP函数创建一个GET参数重定向

请任何帮助,将被视为 感谢

+0

我是正确的理解要基于表单输入的形式作用是动态的? – amflare

+0

这是不能单独用PHP做,你需要使用AJAX(客户端)请求你的PHP发送帕拉姆然后获得响应。 – Akam

+0

这听起来像一个[XY问题(http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – skrilled

回答

1

如果你不需要在你的客户端上看到instance_id,你可以创建一些重定向页面,从数据库中检索instance_id。此页面可能与您的目标页面相同。

<form method="GET" action="<?php echo BASE_URL; ?>"> 
    <div style="color:white">Instructions</div> 
    <input type="number" name="param" /> 
    <input type="hidden" name="action" value="view" /> 
    <input type="hidden" name="controller" value="Solution" /> 

    <input type="submit" value="Solutions Listing" id="button_solutions"> 
</form> 

,并在您的PHP脚本

// instance_id not set 
if (!isset($_GET['instance_id'])) { 
    $args = $_GET; 
    $param = $args['param']; 

    // do something with param and save it to instance_id 
    $instance_id = ... 

    $args['instance_id'] = $instance_id; 

    // create get query 
    $query = http_build_query($args); 

    $url = BASE_URL . '?' . $query; 
    header('Location: ' . $url); 
} else { 
    // instance_id set - do something with it 
    $instance_id = $_GET['instance_id']; 
} 

如果你不能使用这种方式,必须表现出你的INSTANCE_ID的结果的同时,用户进入帕拉姆,你必须使用一个ajax请求,它向服务器发送请求以获取instance_id。

的JavaScript的(使用jQuery)这样做看起来是这样的:

$('input[name="param"]').on('change', function() { 
    $.ajax({ 
     url: '...', 
     data: { param: $(this).val() }, 
     method: 'GET' 
    }).done(function(data) { 
     $('input[name="instance_id"]').val(data); 
    }); 
}); 

php文件得到param如GET价值,应该从你的数据库返回的INSTANCE_ID。