为什么我的form.action与表单提交的内容不同?

时间:2019-04-30 03:58:13

标签: javascript php html get html-form

我正在尝试建立一个表单,以通过用户填写的表单将数据传输到我的php文件中。我想创建自己的GET请求,以简化此请求,但是在提交表单时,它是与创建的URL不同的URL。

我控制台记录了我的form.action并获得了(均为伪造数据):

... / index.php?search1 = 987654321&search2 = 987654321

但是我得到的URL是(我输入987654321):

/index.php?search1=987654321

文件:index.html

$attendance_list = DB::table('daily_attendances')
        ->join('employees', 'employees.card_id', '=', 'daily_attendances.card_id')
        ->select('daily_attendances.*','employees.basic_salary','employees.start_time','employees.over_time_rate',
            DB::raw('SEC_TO_TIME( SUM( TIME_TO_SEC( daily_attendances.delay_time ) ) ) AS delay_time'),
            DB::raw('SEC_TO_TIME( SUM( TIME_TO_SEC( daily_attendances.extra_time ) ) ) AS extra_time'),
            DB::raw('SEC_TO_TIME( SUM( TIME_TO_SEC( daily_attendances.in_use_time ) ) ) AS duty_time'),
            DB::raw('count(daily_attendances.start_time < daily_attendances.in_time) AS delay_day'),
            DB::raw(DB::raw('count(*) as present_day')))
        ->whereRaw($where)
        ->groupBy('daily_attendances.card_id')->get();

文件:helper-functions.js

<form id="searchForm" action="/index.php" method="GET">
    <input type="submit" value="Search" onclick="createActionGetRequest()">
    <br><br>
    <text id="search1Text">Social Security Number</text><input id="searchField1" type="text" name="search1"><br>
    <text id="search2Text"></text>
</form>

2 个答案:

答案 0 :(得分:1)

当您单击表单中的“提交”按钮时,它总是被浏览器调用form.submit()。这意味着进行了2次调用,/index.php?search1=987654321由浏览器进行,/index.php?search1=987654321&search2=987654321由您的js代码进行

您可以将event.preventDefault()添加到createActionGetRequest()以阻止浏览器调用。

function createActionGetRequest(event)
{
   event.preventDefault()
   ...
}

GET方法还将请求查询替换为表单输入值。您可以添加另一个输入,而不是更改form.action。

var input = document.createElement("input"); 
input.type = "text"; 
input.name = "search2"; 
form.appendChild(input); 

答案 1 :(得分:1)

以及一些有关您的代码的建议:

1。将Submit元素更改为按钮类型,以防止触发commit()。

<input type="button" value="Search" onclick="createActionGetRequest()">

2。从input元素连接的值应排除我们不需要的元素。

for (var i = 0; i < elements.length; i++)
{
    if( elements[i].name.startsWith('search')) {
        values.push(encodeURIComponent(elements[i].name) + '=' + encodeURIComponent(elements[i].value));
    }
}