How to make the values entered in controls appear within single quotes in query string

时间:2017-05-16 09:31:11

标签: javascript php html

 <script>
  function myFunction() {
    var query = '?';
    var str = $( "form" ).serialize();
    $( "#results" ).text( query += str );
    
  }
  $( "input[type='sel'], input[type='text']" ).on( "submit", myFunction );
  $( "select" ).on( "submit", myFunction );
   myFunction();
  
</script>
echo'<input  id="submit" type="submit" value="SUBMIT" class="btn btn-success"  name="submit" onclick="myFunction()"/> ';
echo '<p id="results">&nbsp;</p></form>';
here it is javascript for to generate query string for controls so I have butten with id=submit and event onclick=myFunction

how to make this work onclick event and also query string should print on the

tag and what will be the code for insertion please let me knoe the answer

for eg: ?gender='Male'&city='dwd'

1 个答案:

答案 0 :(得分:0)

要在数据库中保存查询字符串,您不需要在javascript中执行此操作,请参阅以下示例:

test.php的

<form method="post">
    <label> Name
        <input name="query[name]" type="text">
    </label>

    <label> Email
        <input name="query[email]" type="text">
    </label>

    <label> Phone
        <input name="query[phone]" type="text">
    </label>

    <button type="submit">Submit</button>
</form>

<?php

if ($_POST && isset($_POST['query'])) {
    $query = '?'. http_build_query($_POST['query']);

    //save the value of query in the database
    echo $query;
}

上面的示例提交数组中所有输入的值,并使用http_build_query

构建查询

并使用ajax:

test.php的

<script type="text/javascript" src="/js/jquery.min.js"></script>
<form method="post">
    <label> Name
        <input name="query[name]" type="text">
    </label>

    <label> Email
        <input name="query[email]" type="text">
    </label>

    <label> Phone
        <input name="query[phone]" type="text">
    </label>
    <button type="submit" >Submit</button>
</form>
<script>
    $('form').on('submit',function(e){
        e.preventDefault();
        e.stopPropagation();

        $.ajax('/ajax.php', {
            method: 'POST',
            data: $('form').serialize()
        })
    });
</script>

ajax.php

<?php
if ($_POST && isset($_POST['query'])) {
    $query = '?'.http_build_query($_POST['query']);

    //save the value of query in the database
    echo $query;
}