如何使用PHP将查询字符串修改为普通URL?

时间:2016-10-20 15:58:46

标签: php apache .htaccess mod-rewrite

我有以下html表格:

<div class="row form">
    <div class="col-md-offset-3 col-md-6 col-md-offset-3">
    <form class="form-inline" role="form" method="get" action="<?php echo htmlspecialchars(SITE_URL.'location'); ?>">
        <div class="form-group col-md-10 no-p-m">                      
            <select class="form-control" id="basic" name="location" required>
            <?php
            $get_location = mysqli_query($conn, "SELECT * FROM product_sub_area");
            if(mysqli_num_rows($get_location) == 0 ) {
                $choose = 'No City found';
            } else {
                $choose = 'Choose City';
            }
            ?>
            <option value=""><?php echo $choose; ?></option>
            <?php                                         
            while($get_location_result = mysqli_fetch_array($get_location) ) {
                $location_id = (int) $get_location_result['psub_area_id'];
                $location_name = htmlspecialchars($get_location_result['psub_name']);
                echo "<option value='$location_id'>$location_name</option>";
            }
            ?>                    
            </select>
        </div>
        <div class="form-group col-md-2 no-p-m" id="basic">  
            <input type="submit" class="btn btn-default filter-search" value="BROWSE">
        </div> 
    </form>                
    </div>
</div>  

当我提交此表单时,网址显示如下:

  

http://localhost/freelancer/happiechef/location?location=1

但我需要展示这种类型的网址:

http://localhost/freelancer/happiechef/location/carlifonia

此处/location/是一个名为location.php的网页。我正在使用.htaccess隐藏页面扩展名。

因此,从location.php页面我想得到$_GET['location'] value = $location_id

例如。

$ _ GET [&#39; location&#39;] = 1或2(选择标记选项值)

现有.htaccess代码

ErrorDocument 404 not-found.php
RewriteEngine On        

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^location/([\w-]+)$ location.php?location=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

1 个答案:

答案 0 :(得分:1)

这是一个如何在jQuery中实现这个的例子:

首先,在您的id代码中添加<form>,以便轻松访问:

<form id="formname" class="form-inline" role="form" method="get" action="<?php echo htmlspecialchars(SITE_URL.'location'); ?>">

您还有一个名为id的重复"basic"。请确保只将其保留在<select>标记上,然后删除另一个标记。

然后在你的JS中:

$("#formname").submit(function(event) {
    event.preventDefault();
    var loc = $("#basic option:selected").text();
    window.location.href = '/freelancer/happiechef/location/' + loc;
});

这会将用户转发到网址,例如http://localhost/freelancer/happiechef/location/carlifonia。然后.htaccess会将此网址重写为location.php?location=california